Search code examples
pythonmako

Mako Template 0.8 how to include file where the value is a variable?


I'm trying to do something like this - I have a function that needs to include another template - but dynamically from a variable and I can't seems to do it

# include template A
add_tmpl("a.html")

# include template B
add_tmpl("b.html")

<%def name="add_tmpl(include_file)">
   <%inherit file="${include_file}" />    # doesn't work
   <%include file="${include_file}" />    # work but I need to define args=""
<%/def>

Errors list while debugging:

# NameError: global name 'include_file' is not defined
<%inherit file="${include_file}" />

# mako.exceptions.SyntaxException: Expected: %> in file 'templates/index.html' at line: 220 char: 9
<%inherit file=${include_file} />    # and same for:
<%inherit file=include_file />

# Can't find template ( thought maybe it will know it's a variable )
<%inherit file="include_file" />

This is where I run out of ideas ... any idea ?

Temporary solution

I'm writing this until I'll get a real solution/answer from others.

Since the problem is when I include vs inherit - I also need to define the args="" dynamically - but each use of the add_tmpl() function has different amount of variables ( in later version in Mako you don't need to, but I can't upgrade ).

So as a temp solution I've done something like this:

# include template A
add_tmpl("a.html", var1=value1, var2=value2, var3=value2)

# include template B
add_tmpl("b.html", var3=value3)

<%def name="add_tmpl(include_file, include_args)">   
   <%include file="${include_file}" args="**include_args" />
<%/def>

Solution

  • Found another option.

    Apperantly there's a variable called context and it holds kwargs in it. So we can simply write **context.kwargs to extract all variables in the current template and pass them on as is

    And we can pass ALL variables to the included template with

    <%include file="${include_file}" args="**context.kwargs" />
    <%include file="${include_file}" args="var1=var1, **context.kwargs" />
    

    More about it: http://docs.makotemplates.org/en/latest/runtime.html#mako.runtime.Context