0

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 ?

asked May 1, 2013 at 14:28
1

1 Answer 1

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.

answered May 1, 2013 at 16:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.