I am using django and jinja2 and have something like this in one of my html pages
<p><strong>Q. {{ _("What products will you accept?") }}</strong></p>
<p class="style3"><strong>A: </strong>{% trans myurl=request.url('start') %}A list of qualifying devices is available once you start your trade-in estimate. <a href= {{myurl}}>Click here</a> to learn what your old device is worth.</p>{% endtrans %}
When I run django-admin.py makemessages, "What products will you accept?" is the only string that gets processed. I thought that wrapping a string with the {% trans %} block also marks that string or is this a wrong statement?
What is the best technique to mark that second string (it's tricky because of the request.url variable)
I've tried {{ _("A list of qualifying devices is available once you start your trade-in estimate. <a href= {{ request.url('start') }}>Click here</a> to learn what your old device is worth.")|safe }} but then the link doesn't work properly.
To translate a block like that you need to use the {% blocktrans %} template tag,
{% blocktrans with myurl=request.url('start') %}
A list of qualifying devices is available once you start your trade-in estimate. <a href= {{myurl}}>Click here</a> to learn what your old device is worth.</p>
{% endblocktrans %}
However, I'm not sure you can call a function like that anywhere in a template like you are attempting.
Consider instead passing myurl in as a template variable, and then using smaller chunks of text. This increases reuse of the translations - especially for small common blocks like "Click here".
{% blocktrans %}
"A list of qualifying devices is available once you start your trade-in estimate."
{% endblocktrans %}
<a href= {{myurl}}>{% trans "Click here" %}</a>
{% trans "to learn what your old device is worth." %}
Also, when using HTML and template tags, try and keep them correctly nested. For example, in your code you would have:
<p>... {% blocktrans %}... </p>{% endblocktrans %}
Instead try to nest them like so:
<p>... {% blocktrans %}... {% endblocktrans %}</p>
This is especially useful for IDEs that can auto indent and fold content and helps readability.
Related
Maybe I'm doing it wrong (tried several ways to achieve my goal) or overlooking something here.
What I'd like to achieve is this:
When I use the Live-search function, I get categories containing the search keyword (like: Paint -> Paint buckets, Paint brushes, Paint colors etc.) which works like a charm. The one thing I need is to style the searched keyword in the presented categories like:
Paint bucket,
Paint brushes,
Color paint
This is the code I have at the moment:
{% if (products.length + categories.length + pages.length) == 0 %}
<div id="Pi56dYpB" class="undefined"> No results for:
<b>{{ query }}</b>...
</div>
{% endif %}
{% if categories.length > 0 %}
<div class="categories">
{% for category in categories %}
{% if loop.index < 7 %}
<a class="p-0" href="{{ category.url }}" style="all:inherit;">
<h3 id="bvwiyjEN" class="undefined">{{ category.name|replace({{ query }}: "<strong>"{{ query }}"<strong>"})|raw }}</h3>
</a>
{% endif %}
{% endfor %}
{% endif %}
Unfortunately this isn't working. I did check if the {{ query }} value is accessible with this simple line of code:
<h3 id="bvwiyjEN" class="undefined">{{ category.name }} - {{ query }}</h3>
No problems found here.
Did I use the wrong syntax in my code maybe? Any help would be appreciated!
replace({{ query }}) is the wrong syntax - replace(query) should work, as you don't want to echo the variable query here
As Nico Haase pointed out already, {{ ... }} is used to output variables, this translate to something like <?php echo $foo; ?> and can't/shouldn't be used inside statements
Furthermore, the filter replace expects an array of keys to replace with the values.
You would need to change your code to the following:
{% for category in categories %}
{{ category|replace({ (query): '<strong>'~query~'</strong>',})|raw }}
{% endfor %}
demo
Some notes:
The filter replace uses the PHP function strtr in the background. This mean the output will be case-sensitive. If you don't want this, I'd advice you to follow through here
Wrapping the key with parantheses is mandatory. This will force twig to evaluate/interpolate the value of the key - demo
I work in SublimeText 3. When writing Django templates I have a mixture of html and functions.
I like to indent my code so that block, if and other such statements are indented. For example:
Manual formatting
{% extends "accounts/base.html" %}
{% block content %}
<h1>Password changed</h1>
<p>Your password was changed.</p>
{% endblock %}
However, when I run any autoformatter HTML-CSS-JS-Prettify it ignores these brackets and treats them as text:
After formatting
{% extends "accounts/base.html" %}
{% block content %}
<h1>Password changed</h1>
<p>Your password was changed.</p>
{% endblock %}
Although plugins like Djaneiro give great tag highlighting, I haven't been able to find a way to get SublimeText to treat these as tags.
Has anyone had any luck?
This is a late answer, but I would like to mention a Django template formatter that I've created myself: DjHTML. You can install it using pip install djhtml.
Let's say template.html contains the following:
{% extends "accounts/base.html" %}
{% block content %}
<h1>Password changed</h1>
<p>Your password was changed.</p>
<script>
$(function() {
console.log("Password changed!");
});
</script>
{% endblock %}
Then running djhtml template.html will give the following output:
{% extends "accounts/base.html" %}
{% block content %}
<h1>Password changed</h1>
<p>Your password was changed.</p>
<script>
$(function() {
console.log("Password changed!");
});
</script>
{% endblock %}
It's easiest to use DjHTML as a pre-commit hook, so that templates will be automatically indented when you run git commit. Instructions on how to configure pre-commit can be found in the README.
There isn't one for sublime text as far as I can tell. I have no source I can quote on this, but I have basically searched nothing came up.
This discussion is by any means old, but active. I found this really old ticket about formatting standards for Django and it has been updated 9 Months ago to basically say they are "in favour of standards" and the proposed formatting for templates would be:
<ul>
{% for x in y %}
<li>{{ x }}</li>
{% endfor %}
</ul>
They also made a place happen that holds information about formatting guidelines in Django.
You might find this discussion interesting as well. It's old too, but it highlights the confusion about formatting in Django and the DIY solutions people came up with to cope.
There is PEP 8 for Python, but I haven't seen a preferred indentation guideline for django templates.
What I mean is, I normally indent blocks like this:
<span>outside</span>
{% if condition %}
<span>within condition</span>
{% endif %}
<span>outside</span>
While this looks good on the editor, but it will look crap on view source like this:
<span>outside</span>
<span>within condition</span>
<span>outside</span>
It would even look worse within the HTML indentation, see below:
<div>
<span>outside</span>
{% if condition %}
<span>within condition</span>
{% endif %}
</div>
will become:
<div>
<span>outside</span>
<span>within condition</span>
</div>
While I agree having better layout in editor is way way more important, but I also get paranoid about the generated messy HTML source code.
I am currently following my own convention in django template guideline for consistency matter. The rule is simple:
Django tag does NOT increase the indentation level
HTML tag does increase the indentation level
It does not matter how many nested Django Tag you have, you should still on the same level of indentation. I consider this as the trade off for putting logic in templates which should be minimized if possible to avoid confusion.
<html>
<body>
<ul>
{% if condition %}
{% for item in menu_item %}
<li>{{ item }}</li>
{% endfor %}
{% endif %}
</ul>
<main>
{% block content %}
<p>Hello World</p>
{% endblock content %}
</main>
</body>
</html>
Side note
I am using 2 spaces for HTML indentation, because HTML tends to have a very deep nested.
For Vim user, please note that the syntax is not html but htmldjango
Thus my ~/.vimrc looks something like:
autocmd Filetype htmldjango setlocal ts=2 sts=2 sw=2 expandtab
Depending your editor, there are ways to set a specific indent width for HTML files.
As for the Django tags, it is actually a good thing not to not add a indent level. See that example:
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Would be rendered like so:
<ul>
<li>Bacon</li>
<li>Ninja</li>
<li>Tumbleweed</li>
</ul>
And we do not want the two levels of indent. Instead:
{% block content %}
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endblock content %}
My apologies for reviving an old question, but I think the way Emacs' web-mode.el indents Django templates deserves a mention here:
{% block content %}
<div
id="1"
class="fancy"
>
{% if link %}
<a href="{{ link }}">
Click here
</a>
{% endif %}
</div>
{% endblock %}
As you can see, it indents both Django tags and HTML tags, as well as multiline HTML tags. It supports <style> and <script> tags too. In fact, I like this behavior so much that I created DjHTML, a standalone indenter and a pre-commit hook that uses the same indentation rules as web-mode.
I think this is more of a personal preference and what is easy to read and easy to understand in the future (my time limit is "after six months") would be a better alternative than some cookbook recipes. What I use is a two type approach, not just for Django templates but for any language that accepts free formatting of the code. As such I format not critical portions as just left justified block of lines which is an admittedly eyesore but I tend to just ignore them so I can focus on important parts which is extensively indented, preferably in general single action per line and indented at each semantic group change thus all parent/child grouping, nested elements etc. are visible with just one look only.
{% if error_message %}
<p>
<strong>{{error_message}}</strong>
</p>
{% else %}
<table border>
<tr>
<td>
{{degerlendirme.adi}}
</td>
</tr>
<tr>
<td>
<table border>
<tr>
<td>
Tip
</td>
<td>
{{ tip }}
</td>
</tr>
<tr>
<td>
Açıklama
</td>
<td>
{{ degerlendirme.aciklama }}
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<form action="{% url 'perf:degerlendirme' degerlendirme.id %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="OK" />
</form>
</td>
</tr>
</table>
{% endif %}
I usually use Eclipse and there are several good HTML editing tools that you can install into that environment. I try to use them, but prefer to depend solely on indentation for ease of reading/coding/analysis cycle. That is mainly because I regularly need to use other editors, mostly vi. In this case if I rely mainly on Eclipse or whatever IDE I was using for understanding the code vi, nano or other text editors would make my life miserable.
As one of my professors said in a classroom, lots of years ago, spaces are free and tabs are even cheaper.
One last note; Once I needed to remove all white space from a Django template that was creating enormous nested tables in order to improve run time performance. Such might be needed for certain cases. In similar situations it is better to keep one working copy and generate runtime copy from that by a script or tool. I know that, there are some HTML de-clutter tools. In my case, tools I tried corrupted the template and I needed to perform that operation by hand.
I know that it is possible to set context variables when including a Django template from another template using
{% include "default_table.html" with table_header=table_header1 table_data=table_data1 %}
or
{% with "My data" as table_data %}
{% include 'default_table.html' %}
{% endwith %}
My issue with this is that both approaches don't let me define multiline variables (unless they are based on a previous multiline variable of course).
My specific usecase is this
<!-- widget.html -->
<div class="box">
<div class="title">{{ title }}</div>
<div class="title">{{ body }}</div>
</div>
and I'd like to be able to set a longer text for the body context variable. This will make is possible for me to reuse common widget HTML in various places. Can this be done?
I've been searching a bit on http://djangosnippets.org for an über {% with ... %} template tag, but haven't found any so far.
This Django snippet kinda solves my issue: http://djangosnippets.org/snippets/1860/ But I'd love to be able to set context variables instead of defining {% localblock step_ready_js %}{% endlocalblock %} in my widget HTML.
I have some static text that needs to show up at 2 locations within a 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 the above by duplicating the above text at 2 different locations in my template file(as shown above).
I could also create a model which will store the text(This is DRY but cost a call to the DB for a simple task)
I'm thinking of using include template but that's probably not the best way to achieve my goal.
What's the best way to do it?
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.
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.
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
Create a custom template tag (this one makes the most sense based on how you've described your problem above).
Create a base template which has the text in it at the correct location and then inherit off of it for your "2 locations"
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)
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:
http://bitbucket.org/hakanw/django-better-chunks/
http://github.com/bartTC/django-generic-flatblocks
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
If the included text gets bigger, use an 'include' tag.
{% include "myapp/helptext.html" %}
GrtzG