2013-05-01 82 views
0

我正在爲我的項目製作一些通用模板,如下面給出的消息模板。有沒有辦法在django模板中使用變量設置塊的名稱?

{% extends base_name %} 

{% block main-contents %} 

    <h2>{{ message_heading }}</h2> 

    <div class="alert alert-{{ box_color|default:"info" }}"> 
     {{ message }} 

     {% if btn_1_text and btn_1_url %} 
      <a href="{{ btn_1_url }}" class="btn btn-{{ btn_1_color }}">{{ btn_1_text }}</a> 
     {% endif %} 

     {% if btn_2_text and btn_2_url %} 
      <a href="{{ btn_2_url }}" class="btn btn-{{ btn_2_color }}">{{ btn_2_text }}</a> 
     {% endif %} 

    </div> 

{% endblock %} 

我可以通過模板變量設置基本模板的名稱。我的問題是是否有方法使用模板變量設置塊的名稱。通常我使用塊名稱的主要內容幾乎所有我的項目。但是,這並不是所有的項目。如果這是不可能的使用模板有沒有辦法使用python代碼重命名塊?

+0

檢出,http://stackoverflow.com/questions/13316180/use-of-variables-in-django-template-block-tags可能有幫助 – 2013-05-01 14:39:26

回答

1

我發現了一個黑客。我不知道這是否有任何後遺症。任何人都可以驗證這一點?

def change_block_names(template, change_dict): 
    """ 
    This function will rename the blocks in the template from the 
    dictionary. The keys in th change dict will be replaced with 
    the corresponding values. This will rename the blocks in the 
    extended templates only. 
    """ 

    extend_nodes = template.nodelist.get_nodes_by_type(ExtendsNode) 
    if len(extend_nodes) == 0: 
     return 

    extend_node = extend_nodes[0] 
    blocks = extend_node.blocks 
    for name, new_name in change_dict.items(): 
     if blocks.has_key(name): 
      block_node = blocks[name] 
      block_node.name = new_name 
      blocks[new_name] = block_node 
      del blocks[name] 


tmpl_name = 'django-helpers/twitter-bootstrap/message.html' 
tmpl1 = loader.get_template(tmpl_name) 
change_block_names(tmpl1, {'main-contents': 'new-main-contents}) 

這似乎現在工作。我想知道這種方法是否有任何後續影響或其他問題。

相關問題