0

以下に示すメッセージ テンプレートのようなプロジェクト用の一般的なテンプレートをいくつか作成しています。

{% 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 %}

テンプレート変数を使用してベース テンプレートの名前を設定できます。私の質問は、テンプレート変数を使用してブロックの名前を設定する方法があるかどうかです。通常、ほとんどすべてのプロジェクトでブロック名 main-contents を使用します。しかし、それはすべてのプロジェクトに認められているわけではありません。テンプレートを使用してこれが不可能な場合、Python コードを使用してブロックの名前を変更する方法はありますか?

4

1 に答える 1

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

これは今のところうまくいくようです。この方法に後遺症やその他の問題があるかどうかを知りたいです。

于 2013-05-01T16:36:05.470 に答える