IsNullOrEmpty(string)和List.数比;0美元的胡须

本文关键字:美元 胡须 数比 List string IsNullOrEmpty | 更新日期: 2023-09-27 17:52:33

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

我想知道是否有使用这个模板引擎,并有两个条件来检查

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

谁能指导我如何创建像上面这样的标签?

IsNullOrEmpty(string)和List.数比;0美元的胡须

你可以尝试创建一个自定义的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. 任何
  3. 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;
        }
    }
    
  4. 注册两个标签

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