0

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.

Community
  • 1
  • 1
raylu
  • 2,630
  • 3
  • 17
  • 23

2 Answers2

2

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

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

Eric Conner
  • 10,422
  • 6
  • 51
  • 67
  • But these are just short strings: one-line section headers. Having to create a file for each one is worse than duplicating, I think, and so is putting these static strings in the view. – raylu Apr 09 '11 at 21:17
  • 1
    Hmm. I see your point. You could use a template tag similar to this snippet: http://www.soyoucode.com/2011/set-variable-django-template, but I'm not sure it's a great idea to subvert the template system in that way. Maybe the best thing to do is to add the strings you want to display to a settings file of some sort as constants and then pass them to the template context through your view. – Eric Conner Apr 09 '11 at 22:16
0

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 %}
Brad Montgomery
  • 2,621
  • 1
  • 24
  • 24
  • Unfortunately, the content sections are huge. Also, they just don't belong in the views... – raylu Apr 11 '11 at 08:04
  • I (probably falsely) assumed that the content would be queried using the orm. So instead of hard-coding content, it'd look something like: "content = model_instance.content". If this isn't the case, it sounds like you might consider the inclusion tag suggestion. – Brad Montgomery May 14 '11 at 02:55