[Django]-How do I DRY up common text in a Django template?

7👍

Definitely use Inclusion Tags:

http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags

The tag file would either be something super simple like just the text “This is a static text” or the entire block:

{% if something %}
This is a static text
{% else %}
Something else happened
{% endif %}

“something” can be passed as a variable to the template tag so you can use that entire block in a variable way.

4👍

I use the django internationalization to do that. So in my apps/template I just write the key, and in the .po files is the value of the keys.

{% load i18n %}

<div>
{% if something %}
    {% trans "static" %}
{% else %}
    {% trans "something else" %}
{% endif %}
</div>

And in my .po file:

msgid "static"
msgstr "This is a static text"

msgid "something else"
msgstr "Something else happened

Besides useful for multi-language, it’s much easier for copy writing just in case you want to change it in the future because you can just look unto one file instead of browsing several templates.

2👍

There are several ways, but it probably depends on what the text is and how often it will be used. It’s hard to recommend a specific choice without full details

  1. Create a custom template tag (this one makes the most sense based on how you’ve described your problem above).
  2. Create a base template which has the text in it at the correct location and then inherit off of it for your “2 locations”
  3. Put the static piece of text in a settings file and pass it to the template renderer via Context (probably not the best idea, but depending on what you’re doing it could be a possibility)

2👍

You could use flatblocks : http://github.com/zerok/django-flatblocks

or chunks : http://code.google.com/p/django-chunks/

Those may be overkill for your problem, since they store your snippets in the database, but they add the benefit of making it possible to edit them via the admin.

{% load chunks %}
<div>
{% if something %}
    {% chunk "something" %} 
{% else %}
    {% chunk "something_else" %}
{% endif %}
</div>

There are lots of forks or similar projects, for example:

👤kioopi

0👍

I have a file like Java properties that I use for all of my resource strings. I just serve up the one that I want. Keeping these in one place also makes translating easy.

Ex.:

welcome_msg="hello user!" 
thank_you="thank you" 
goodbye_msg="goodbye, " + thank_you
👤geowa4

0👍

If the included text gets bigger, use an ‘include’ tag.

{% include “myapp/helptext.html” %}

GrtzG

Leave a comment