Hello I want to know if I can use ugettext_lazy as _ in the templates of django because I want to replace the tags of {% trans %} and {% blocktrans %} because I don't want to make the messages.
I want to do something like this:
<h1>_('hello')</h1>
Instead of this:
<h1>{% trans 'hello' %}</h1>
Thanks
It's not possible to call any function from a template that takes any arguments. You have to write either tag or filter but I would suggest you to stick with the trans block.
I want to say that <h1>_('hello')</h1> this functionality not possible in django template.
but we have another way of like this with custom templatetag that support your way for translate string in template
{% some_tag _("Page not found") value|yesno:_("yes,no") %}
above added string will work as translation in django.
Read from django documentation https://docs.djangoproject.com/en/1.11/topics/i18n/translation/#string-literals-passed-to-tags-and-filters
Related
Is there any way to completely turn off django auto_escaping when rendering a template within the view code (for an email for example):
from django.template import Context, Template
subject_template_string = "Hi {{ customer.name }}"
subject_template = Template(subject)
context = Context({'customer':MyCustomerModel.objects.get(pk=1)})
subject = subject_template.render(context)
If customer.name is something like "Jack & Jill" - the subject looks like "Hi Jack &\amp; Jill" (without the backslash!)
is there something like
subject = subject_template.render(context, autoescape=False)
edit: The actual templates are created by the client in the database, I'm hoping to avoid having to say add |safe to all templates where this might happen...
Disabling it globally is usually a bad idea since you can easily forget it. I would recommend using the templatetag to disable it for that portion of your template instead.
Something like this:
{% autoescape off %}
This will not be auto-escaped: {{ data }}.
Nor this: {{ other_data }}
{% autoescape on %}
Auto-escaping applies again: {{ name }}
{% endautoescape %}
{% endautoescape %}
How about using mark_safe:
Explicitly mark a string as safe for (HTML) output purposes. The
returned object can be used everywhere a string or unicode object is
appropriate.
It marks a string as safe, so, you should take customer.name out and pass to the template:
from django.utils.safestring import mark_safe
customer = MyCustomerModel.objects.get(pk=1)
context = Context({'customer_name': mark_safe(customer.name)})
subject = subject_template.render(context)
Though, control what is safe or not is better to do inside the template itself, that's why using autoescape should be preffered.
Use Django's autoescape tag:
{% autoescape off %}
{{ body }}
{% endautoescape %}
for more info, check out the docs here.
This is untested, but based on source code review it looks like the context object can take autoescape as a key.
context = Context({'customer':MyCustomerModel.objects.get(pk=1), 'autoescape': False})
subject = subject_template.render(context)
That said, that's a pretty sweeping change. If you know what values the templates might be looking for, it's probably better to use mark_safe on those values and pass in the predefined options. That would have the added benefit of not risking the possibility of the client template calling a method with side effects on the customer. The first time someone writes a template and puts in {{ customer.delete }}, you have a problem.
Just came back to answer my own question with a simple solution, and there were already 4 answers.. thanks.
This is what I've gone with:
subject_template = Template(u'{%% autoescape off %%}%s{%% endautoescape %%}' % email.subject)
I recently discovered a neat trick to avoid polluting the gettext translation files for Django with unnecessary markup. If you want to make an email address clickable, you can use the urlize filter after the trans string argument, like this:
{% trans "Contact us at foo#bar.com"|urlize %}
Is there any way to apply the same trick to the result of a blocktrans tag?
There is a filter block tag that lets you apply one or more filters to the contents of a block, so you can use it like this:
{% filter urlize %}
{% blocktrans %}Contact us at at foo#bar.com{% endblocktrans %}
{% endfilter %}
See Django docs.
Using Django's built-in yesno filter, I need to insert one of these values:
The word "I"
The value of the variable owner_name
Here's the code I've tried to use in my template:
"Look what {{ is_owner|yesno:"I,{{ owner_name }}" }} created!"
Using the code above causes the following error:
Could not parse the remainder: ':"I,{{ owner_name' from
'is_owner|yesno:"I,{{ owner_name'
So how do I escape a variable inside a filter's argument?
Another thing you can do is concatenate the arguments using the with template tag and add filter:
{% with yesno_args="I,"|add:owner_name %}
"Look what {{ is_owner|yesno:yesno_args }} created!"
{% endwith %}
I think this is simpler than having to add a custom filter.
You can create a custom filter to do what you want.
It would look something like {{ is_owner|my_yesno:owner_name }}
With the custom filter
from django.template.defaultfilters import yesno
def my_yesno(value, arg):
yes_no_list = ['I', arg]
return yesno(value, yes_no_list)
This would let you reuse yesno while creating the list in your wrapper my_yesno. You can alternatively just write your own logic if you want to do something differently as well. Be sure to {% load %} your custom filter as well.
I have the following code in my template:
{% for req in user.requests_made_set.all %}
{% if not req.is_published %}
{{ req }}
{% endif %}
{% empty %}
No requests
{% endfor %}
If there are some requests but none has the is_published = True then how could I output a message (like "No requests") ?? I'd only like to use Django templates and not do it in my view!
Thanks
Even if this might be possible to achieve in the template, I (and probably many other people) would advise against it. To achieve this, you basically need to find out whether there are any objects in the database matching some criteria. That is certainly not something that belongs into a template.
Templates are intended to be used to define how stuff is displayed. The task you're solving is determining what stuff to display. This definitely belongs in a view and not a template.
If you want to avoid placing it in a view just because you want the information to appear on each page, regardless of the view, consider using a context processor which would add the required information to your template context automatically, or writing a template tag that would solve this for you.
Django treats {{ var }} as some variable in its template. How can I escape {{ var }} or {{ or }} such that django does not treat it as variable.
<p>"{{ some text }}"</p> Should prints exactly the same.
Django 1.5 introduced {% verbatim %} template tag. It stops template from parsing contents of this tag:
{% verbatim %}
{{ var }}
{% endverbatim %}
will be rendered as:
{{ var }}
I believe you are looking for the templatetag template tag.
As the linked-to doc states,
Since the template system has no concept of "escaping", to display one of the bits used in template tags, you must use the {% templatetag %} tag.
For example:
<p>"{% templatetag openvariable %} some text {% templatetag closevariable %}"</p>
will appear as so:
<p>"{{ some text }}"</p>
Edit: I don't really recommended this because it's not very clean, but it's still an option.
I was searching for one that I could use with JQuery Templates and figured a way to do it without tags or filters. This is as short as I could get it:
{{ "{{ any text }" }}}
Is printed as:
{{ any text }}
Why it works? Any text within {{}} is displayed as is, as long as it doesn't have two closing braces }} in a row. Then there are three brackets in a row, django interprets two first ones as end of the variable leaving one additional closing brace.
You can try escaping with html character escapes like:
{ = {
} = }
<p>"{{ some text }}"</p>
Update
In case anyone is trying to use the actual tags for javascript, verbatim is a better solution:
Stops the template engine from rendering the contents of this block tag.
{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}
if you simply need to use {{ }} as a variable for template framework like angularjs, then following maybe simpler:
in your <app path>/templatetags/ngvar.py , add
from django import template
register = template.Library()
#register.simple_tag
def ngvar(var_name):
return "{{%s}}" % var_name
and in template, do
{% load ngvar %}
{% ngvar "variable name" %}
if ngvar.py is the first template tag, then make sure to add __init__.py file to the templatetags directory
Another option would be to add a word joiner (zero width no-break space) between each curly bracket:
<p>"{{ some text }}"</p>
Although the above answers can solve the original problem, I add some hack around here for those who are scratching their heads like me.
Some times, we want to render a single brace followed by a variable. For example, in BibTeX, there may be something look like this:
#MISC{hu2012-spectral,
author = {Hu, Pili},
title = {Spectral Clustering Survey},
howpublished = {GitHub, https://github.com/hupili/tutorial/tree/master/spectral-clustering},
month = {May},
year = {2012}
}
Those bib fields come from template variables. If you write
title = {{{title}}},
jinja can not compile and raise an error. If you write
title = { {{title}} },
there will be extra blanks. The hack around is to store '{' and '}' as variables and use later.
{% set lb = '{' %}
{% set rb = '}' %}
...
#MISC{{lb}}{{ meta.bib_key }},
author = {{lb}}Hu, Pili{{rb}},
title = {{lb}}{{ meta.title }}{{rb}},
howpublished = {{lb}}GitHub, https://github.com/hupili/tutorial/tree/master/{{ auto.path}}{{rb}},
month = {{lb}}{{ meta.month }}{{rb}},
year = {{lb}}{{ meta.year }}{{rb}}
}
This looks clumsy but it is the best I find so far. If you have a cleaner solution, please tell me.
This template tag (designed for use with jQuery Templates) might do the trick. It let's you wrap content you don't want Django to interpret as variables with a template tag.
it can be solved by avoing adjacent angular backets, if its inside javascript code then you can write
'{'+'{address.'+key+'}}'
I used this to print jinja variables into another template,using javascript.
Jinja, which is what is being used for the templates, offers several suggestions for escaping here. What has worked best for me is using something like "{% raw %}{{ some text }}{% endraw %}"