How can I dry shared text in a Django template?

I have static text that should appear in two places in the template.

For example:

<div>
{% if something %}
    This is a static text
{% else %}
    Something else happened
{% endif %}
</div>
... more html
<span>
{% if something %}
    This is a static text
{% else %}
    Something else happend
{% endif %}
</span>
  • I can do this by duplicating the above text in two different places in the template file (as shown above).
  • I could also create a model that will store text (this is DRY, but cost a DB call for a simple task)
  • I am thinking of using include template, but this is probably not the best way to achieve my goal.

What is the best way to do this?

+3
source share
6 answers

Definitely use inclusion tags:

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

, " " :

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

"-" , .

+7

django internationalization . / , .po - .

{% load i18n %}

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

.po:

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

msgid "something else"
msgstr "Something else happened

, , , , , .

+4

, , , , . .

  • ( , , ).
  • , , "2 "
  • Context (, , , , )
+2

: http://github.com/zerok/django-flatblocks

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

, , , .

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

, :

+2
source

I have a file similar to Java properties that I use for all resource strings. I just serve what I want. Keeping them in one place also facilitates translation.

Example:.

welcome_msg="hello user!" 
thank_you="thank you" 
goodbye_msg="goodbye, " + thank_you
0
source

If the included text gets larger, use the 'include' tag.

{% include "myapp / helptext.html"%}

GrtzG

0
source

Source: https://habr.com/ru/post/1720505/


All Articles