Question

I have a large-ish set of messages, specific to a single page, of which I might night to show any combination of. To simplify adding new messages (the large number is going to get even larger in the short term), and to prevent having a giant if/elif block with an entry for each one, I wanted a way to include all of the relevant templates without having to update the template everytime a new message was added. My though was for dict representing the message to include it's template. This was my attempt at doing so:

<div class="item-content" id="results_content">
  <ul class="unstyled">
     %for msg in c.page_messages:
       <%include file="${msg.get('template_path')}" args="message=msg"/>
     %endfor
  </ul>
</div>

This produces an error at the %include tag:

TypeError: 'NoneType' object has no attribute '__getitem__'
  1. Can it be confirmed whether or not I can use a template variable an include tag, I can't seem to find anything specifically stating either way if I should expect this to work.
  2. If this is not something that will work, is there another way that I can accomplish the same thing? ie - A new message can be added, without having to modify this template code that pulls in each messages template.
Was it helpful?

Solution

It looks like you can use variables within the include tag in the manner you describe. From the docs:

All tags have a set of attributes which are defined for each tag. Some of these attributes
are required. Also, many attributes support evaluation, meaning you can embed an     
expression (using ${}) inside the attribute text:

<%include file="/foo/bar/${myfile}.txt"/>

My guess is that c.page_messages isn't an iterable of dictionaries at this point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top