2013-10-10 60 views
1

我有一組特定於單個頁面的消息,其中我可能會在夜晚顯示任意組合。爲了簡化添加新消息(在短期內大數量將會變得更大),並且爲了防止每個條目都有一個巨大的if/elif塊,我想要一種包含所有相關模板的方式,而無需每次添加新消息時必須更新模板。我雖然是爲代表消息包括它的模板的字典。這是我在做這樣的嘗試:動態設置Mako模板以包含另一個模板

<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> 

這在%產生一個錯誤包括標籤:

TypeError: 'NoneType' object has no attribute '__getitem__' 
  1. 是否可以確認我是否能使用模板變量的包括標籤,我似乎無法找到任何具體說明任何方式,如果我希望這個工作。
  2. 如果這不能起作用,還有另一種方法可以完成同樣的事情嗎?即 - 可以添加新消息,而不必修改此模板代碼來引入每個消息模板。

回答

4

看起來你可以用你描述的方式在include標籤中使用變量。 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"/> 

我的猜測是,c.page_messages是不是在這一點詞典的迭代。