Search code examples
c#.net-coreliquiddotliquid

Subtag context in DotLiquid (with forms)


I'd like to be able to access the object passed to a form tag in DotLiquid within child tags. Something like this:

{% form '/action' requestObject %}
    {% textinput Name %}
    <button type="submit">Create Request</button>
{% endform %}

Where the textinput tag looks for a name field on requestObject and then puts the value into a text input field. My liquidese is a rather rusty so if I'm going about this all wrong I'm open to coherent screaming about what a dolt I am and what I need to do to be better.


Solution

  • This is easily done in the tag renderer with Context's Stack:

    public class Form : Block
    {
        // public override void Initialize...
        public override void Render(Context context, TextWriter writer)
        {
            context.Stack(() =>
            {
                context["form_obj"] = new FormObject();
                result.Write("<form>");
                base.Render(context, result);
                result.Write("</form>");
            }
        }
    }
    

    Before running the action passed to it, Stack pushes a new Hash variable stack (that looks up the chain for unset variables) and then pops it at the end. Perfect for localized scope of variables.