gpt4 book ai didi

c# - IsNullOrEmpty(string) 和 List.Count > 0 in mustache-sharp

转载 作者:行者123 更新时间:2023-11-30 16:48:29 34 4
gpt4 key购买 nike

我使用 mustache-sharp作为模板引擎

我想知道到底有没有用这个模板引擎,有两个检查条件

1) IsNullOrEmpty(string)  => e.g. {{#IsNullOrEmpty MyName}}} {{/IsNullOrEmpty}}
2) List.Count > 0 => e.g. {{#Any Persons}} {{/Any}}

谁能指导我如何创建上述标签?

最佳答案

您可以尝试创建一个自定义的 ContentTagDefinition 并在 HtmlFormatCompiler 中注册它。

例如:

  1. IsNullOrEmpty

    public class IsNullOrEmptyTagDefinition : ContentTagDefinition
    {
    private const string conditionParameter = "condition";

    public IsNullOrEmptyTagDefinition()
    : base("IsNullOrEmpty")
    {}

    public override IEnumerable<TagParameter> GetChildContextParameters()
    {
    return new TagParameter[0];
    }

    public override bool ShouldGeneratePrimaryGroup(Dictionary<string, object> arguments)
    {
    object condition = arguments[conditionParameter];
    return isConditionSatisfied(condition);
    }

    protected override IEnumerable<TagParameter> GetParameters()
    {
    return new TagParameter[] { new TagParameter(conditionParameter) { IsRequired = true } };
    }

    protected override bool GetIsContextSensitive()
    {
    return false;
    }

    private bool isConditionSatisfied(object condition)
    {
    if (condition == null)
    {
    return true;
    }

    return condition is string ? string.IsNullOrEmpty(condition as string) : false;
    }

    }
  2. 任何

    public class AnyTagDefinition : ContentTagDefinition
    {
    private const string conditionParameter = "condition";

    public AnyTagDefinition()
    : base("Any")
    {}

    public override IEnumerable<TagParameter> GetChildContextParameters()
    {
    return new TagParameter[0];
    }

    public override bool ShouldGeneratePrimaryGroup(Dictionary<string, object> arguments)
    {
    object condition = arguments[conditionParameter];
    return isConditionSatisfied(condition);
    }

    protected override IEnumerable<TagParameter> GetParameters()
    {
    return new TagParameter[] { new TagParameter(conditionParameter) { IsRequired = true } };
    }

    protected override bool GetIsContextSensitive()
    {
    return false;
    }

    private bool isConditionSatisfied(object condition)
    {
    if (condition is IEnumerable)
    {
    return (condition as IEnumerable).Cast<object>().Any();
    }

    return false;
    }

    }
  3. 注册两个标签

    HtmlFormatCompiler compiler = new HtmlFormatCompiler();
    compiler.RegisterTag(new IsNullOrEmptyTagDefinition(), true);
    compiler.RegisterTag(new AnyTagDefinition(), true);

关于c# - IsNullOrEmpty(string) 和 List.Count > 0 in mustache-sharp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38079566/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com