2013-05-01 155 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}) 

这似乎现在工作。我想知道这种方法是否有任何后续影响或其他问题。

相关问题