I am making some generic templates for my projects like the message template given below.
{% 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 %}
I can set the name of the base template through template variables. My question is whether there is a method to set the name of the block using template variables. Usually I use the block name main-contents for almost all of my project. But that is not granted for all the projects. If this is not possible using template is there a way to rename the block using python code ?
-
Check out, stackoverflow.com/questions/13316180/… might helpMatt Seymour– Matt Seymour2013年05月01日 14:39:26 +00:00Commented May 1, 2013 at 14:39
1 Answer 1
I found a hack. I dont know if this has any after effects. Can any one verify this ?
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})
This seems to work for now. I want to know if this method has any after effects or other issues.