I use mustache-sharp as template engine
I want to know Is there anyway by using this template engine and have two conditions for checking
1) IsNullOrEmpty(string) => e.g. {{#IsNullOrEmpty MyName}}} {{/IsNullOrEmpty}}
2) List.Count > 0 => e.g. {{#Any Persons}} {{/Any}}
Can anyone guide me How can I create tags like above ?
You can try to create a custom ContentTagDefinition and register it in HtmlFormatCompiler.
For example:
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;
}
}
Any
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;
}
}
Register both tags
HtmlFormatCompiler compiler = new HtmlFormatCompiler();
compiler.RegisterTag(new IsNullOrEmptyTagDefinition(), true);
compiler.RegisterTag(new AnyTagDefinition(), true);