简体   繁体   中英

How do I avoid duplicating strings in my Django templates?

I'm wondering how to duplicate a few strings in my templates. Specifically, I'm looking to create a table of contents sort of navigation at the top of my pages with anchor links to content farther down (like http://www.google.com/transparencyreport/faq/ ). I want the links to have the same text as the section headers farther down.

I've thought about using {% with %}, but it seems unwieldy to have to nest everything inside my {% with %} block.

Similar to Whats the best way to duplicate data in a django template? , but I am not inheriting this template anywhere so using {% block %} is not really an option.

This seems like a situation for just using a template variable that you've passed from a view (eg {{ link_name }} ).

You could use also possibly use template inclusion tag that includes another template with your duplicate information.

In your view, you could potentially break your content up so that the headers are individually accessible as template variables. You might store the information associated with each header as a list of dicts:

page_content = [
    { 
         'id':'header1',
         'header': 'Text for Header 1'
         'content' : 'Content Beneath header 1' 
    },
]

Then, in your templates, you could generate your table on contents with something like this:

{% for d in page_content  %}
    <a href="#{{ d.id }}">{{ d.header }}</a>
{% endfor %}

While the content of your page would look something like this:

{% for d in page_content  %}
    <h1 id="#{{ d.id }}">{{ d.header }}</h1><p>{{ d.content }}</p>
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM