我使用mustache-sharp作为模板引擎
我想知道无论如何使用此模板引擎并且有两个条件来检查
1) IsNullOrEmpty(string) => e.g. {{#IsNullOrEmpty MyName}}} {{/IsNullOrEmpty}}
2) List.Count > 0 => e.g. {{#Any Persons}} {{/Any}}
任何人都可以指导我如何创建上述标签?
答案 0 :(得分:1)
您可以尝试创建自定义 ContentTagDefinition 并在 HtmlFormatCompiler 中注册。
例如:
<强> 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;
}
}
<强>任何强>
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;
}
}
注册两个标签
HtmlFormatCompiler compiler = new HtmlFormatCompiler();
compiler.RegisterTag(new IsNullOrEmptyTagDefinition(), true);
compiler.RegisterTag(new AnyTagDefinition(), true);