pythonbottle

How to make an optional include in a bottle template?


I would like to add an optional include in a bottle template.

Unfortunately this does not work as expected:

<foo>

    % include(required_view)

    <%
        try:
            include(optional_view)
        except NameError:
            pass
    %>

</foo>

It does indeed make the optional import, but it stops after that.
(So </foo> is missing from the result.)

I would like to allow for the variable optional_view to be undefined.
Always adding 'optional_view': None to the context would be annoying.
(Not to mention always adding an empty view.)


Solution

  • The end keyword was missing. This works:

    <foo>
    
        % include(required_view)
    
        <%
            try:
                include(optional_view)
            except NameError:
                pass
            end
        %>
    
    </foo>
    

    The right answer came from this followup question.

    Quote from the Bottle documentation about embedded Python code:

    Note that % and <% %> work in exactly the same way. The latter is only a convenient way to type less and avoid clutter for longer code segments. This means that in <% %> blocks, all indented code must be terminated with an end.