Search code examples
c#enumsdotliquid

Handling Enums with DotLiquid templating engine


I'm currently working on a Web project for which I need to be able to send an email. I started using DotLiquid for the templating engine, but I found certain issues with it, the biggest being that it does not seem to be able to handle enums.

I tried to register the type as "Safe" like that Template.RegisterSafeType(typeof(Gender), new string[] { "Male", "Female" });, but it does not seem to work. At best, there is no longer any exception thrown, but the expected result is empty.

<ul>
    {% for f in Model.Friends %}
        {% if f.Gender == Male %}
            <li>
                {{ f.FirstName }} {{ f.LastName }} {{ f.Gender }}
            </li>
        {% endif %}
    {% endfor %}
</ul>

<ul>
    {% for f in Model.Friends %}
        {% if f.Gender == Gender.Male %}
            <li>
                {{ f.FirstName }} {{ f.LastName }} {{ f.Gender }}
            </li>
        {% endif %}
    {% endfor %}
</ul>

<ul>
    {% for f in Model.Friends %}
        {% if f.Gender == 0 %}
            <li>
                {{ f.FirstName }} {{ f.LastName }} {{ f.Gender }}
            </li>
        {% endif %}
    {% endfor %}
</ul>

None of the above were able to return anything. I would be happy with a string or int representation of the enum, but there is nothing for now. Has anyone found a solution to this issue ?

I would like to avoid to "transform" the enum myself in the Drop object as this could be confusing later on.

Thank you.


Solution

  • Ok, so I found the answer if anyone is interested in it.

    When you Register the type, you also have the possibility to specify a Func<object,object> as a second or third parameter depending on the overload you take. This function allows you to specify a conversion value.

    So, in my example, you can do this :

    Template.RegisterSafeType(typeof(Gender), o => o.ToString());
    

    And it starts working.