I'm new in Django and I am trying to search for something in a template if I find it a want to print something, if not I want to print something else.
sth like this:
{% for art in artifacts %}
{% if art.product_component == 'A' %}
<p> something.</p>
{{ found = True }}
{% endif %}
{% endfor %}
{% if not found %}
<p>NA</p>
{% endif %}
I know this is not the right way to do it, but this is just to understand the idea.
how can i do it?
You can write a templatetag for finding product_component == 'A' is exist or not.
your_app_dir/templatetags/product_tag.py
from django import template
from django.template import Library
register = Library()
#register.assignment_tag()
def check_product_component_status(artifacts):
value = [art for art in artifacts if art.product_component == 'A']
if value:
return True
return False
template:
{% for art in artifacts %}
{% if art.product_component == 'A' %}
<p> something.</p>
{% endif %}
{% endfor %}
{% load product_tag %}
{% check_product_component_status artifacts as status %}
{% if not status %}
<p> something.</p>
{% endif %}
Related
The core problem is that handling of wagtail RichTextField and StreamField is radically different in the templates.
I'm trying to accomplish something similar to the following:
{% with post=post.specific %}
{% if post.content_type == 'streamfield' %}
{% include_block post.body %}
{% else %}
{{ post.body|richtext }}
{% endif %}
{% endwith %}
I'm trying to show partials based on a simple condition. My condition is whether an assignment_tag is True or False.
Templatetag:
from django import template
register = template.Library()
#register.assignment_tag
def partner():
return False
Template:
{% load partner_check %}
{% if partner %}
{% block header %}
{% include 'includes/partner_header.djhtml' %}
{% endblock header %}
{% block footer %}
{% include 'includes/partner_footer.djhtml' %}
{% endblock footer %}
{% endif %}
No matter what I set partner to, the blocks still appear. What am I missing?
Firstly, that's not how assignment tags work. You have never actually called the tag; if partner refers to a (non-existent) template variable named "partner". You call an assignment tag by using it on its own along with a variable to assign it to:
{% partner as partner_value %}
{% if partner_value %}...{% endif %}
Secondly, that's not how blocks work either. You can't dynamically define blocks; they are part of the basic structure of a template, not something that is assigned during evaluation.
I accomplished this by using a context_processor (https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-TEMPLATE_CONTEXT_PROCESSORS)
Context Processor:
def partners(context):
return {
'partner': False
}
Template:
{% block header %}
{% if partner %}
{% include 'includes/partner_header.djhtml' %}
{% else %}
{{ block.super }}
{% endif %}
{% endblock header %}
{% block footer %}
{% if partner %}
{% include 'includes/partner_footer.djhtml' %}
{% else %}
{{ block.super }}
{% endif %}
{% endblock footer %}
So, I have a number of objects I wish to render in a loop. I.E. Render each of the 5 latest posts on the home page. Each of these posts will be displayed differently whether or not the user is logged in.
I have a question: How would I go about making this distinction? I imagine having a template like this
{% if user.is_logged_in %}
{% for post in latest_posts %}
post.render_long_form
{% endfor %}
{% else %}
{% for post in latest_posts %}
post.render_short_form
{% endfor %}
{% endif %}
How can I make the functions render_short_form and render_long_form return the appropriate HTML snippits? I would like them to call other templates for rendering under the hood.
Thanks!
Why don't not use {% include %} tag?
{% if user.is_logged_in %}
{% for post in latest_posts %}
{% include 'long_form.html' %}
{% endfor %}
{% else %}
{% for post in latest_posts %}
{% include 'short_form.html' %}
{% endfor %}
{% endif %}
Or, more DRY version:
{% for post in latest_posts %}
{% if user.is_logged_in %}
{% include 'long_form.html' %}
{% else %}
{% include 'short_form.html' %}
{% endif %}
{% endfor %}
I want to put break and continue in my code, but it doesn't work in Django template. How can I use continue and break using Django template for loop. Here is an example:
{% for i in i_range %}
{% for frequency in patient_meds.frequency %}
{% ifequal frequency i %}
<td class="nopad"><input type="checkbox" name="frequency-1" value="{{ i }}" checked/> {{ i }} AM</td>
{{ forloop.parentloop|continue }} ////// It doesn't work
{ continue } ////// It also doesn't work
{% endifequal %}
{% endfor%}
<td class="nopad"><input type="checkbox" name="frequency-1" value="{{ i }}"/> {{ i }} AM</td>
{% endfor %}
Django doesn't support it naturally.
You can implement forloop|continue and forloop|break with custom filters.
http://djangosnippets.org/snippets/2093/
For-loops in Django templates are different from plain Python for-loops, so continue and break will not work in them. See for yourself in the Django docs, there are no break or continue template tags. Given the overall position of Keep-It-Simple-Stupid in Django template syntax, you will probably have to find another way to accomplish what you need.
For most of cases there is no need for custom templatetags, it's easy:
continue:
{% for each in iterable %}
{% if conditions_for_continue %}
<!-- continue -->
{% else %}
... code ..
{% endif %}
{% endfor %}
break use the same idea, but with the wider scope:
{% set stop_loop="" %}
{% for each in iterable %}
{% if stop_loop %}{% else %}
... code ..
under some condition {% set stop_loop="true" %}
... code ..
{% endif %}
{% endfor %}
if you accept iterating more than needed.
If you want a continue/break after certain conditions, I use the following Simple Tag as follows with "Vanilla" Django 3.2.5:
#register.simple_tag
def define(val=None):
return val
Then you can use it as any variable in the template
{% define True as continue %}
{% for u in queryset %}
{% if continue %}
{% if u.status.description == 'Passed' %}
<td>Passed</td>
{% define False as continue %}
{% endif %}
{% endif %}
{% endfor %}
Extremely useful for any type of variable you want to re-use on template without using with statements.
I am looking for way to clean up a template in django. A simple solution would be to break this up into multiple templates, but we do not want to do that.
We basically have the following
{%if data.some_state %}
Display some markup
{% else %}
{%if data.some_state_2 %}
State 2 different html view
{% else %}
{%if data.process_data %}
Display some list of data
{% else %}
No Data to display!
{% endif %} <!-- if data.process_data-->
{% endif %} <!-- if data.some_state_2 -->
{% endif %} <!-- if data.some_state -->
So that is extremely confusing and hard to read. If I could do this in a "function" i would use if/else if or returns.
Is there a way in template language to do something like (stop_processing_template would tell the template we are done... ):
{%if data.some_state %}
Display some markup
{% endif %}
{% django_stop_processing_template %}
{%if data.some_state_2 %}
State 2 different view
{% endif %}
{% django_stop_processing_template %}
{%if data.process_data %}
Display some list of data
{% endif %}
{% django_stop_processing_template %}
No data provided !
I am not sure what your stop processing template logic would do; but a cleaner way to do your logic would be to write a custom tag that takes your arguments and then returns only the HTML relevant to your variables. This way you remove the if/else loops and instead replace all that with a simple {% do_stuff %} tag.
Edit
This is a very simple implementation to give you some idea on how the logic would go.
First, you create templates for each variation and store them somewhere django can find them.
Then, a simple tag that renders the exact template you want (this is non tested, psuedo):
from django import template
from django.db.models import get_model
register = template.Library()
class ProcessData(template.Node):
def __init__(self, var_name):
self.obj = get_model(*var_name.split('.'))
def render(self, context):
if self.obj.some_state:
t = template.loader.get_template('some_markup_template.html')
result = 'something'
else:
if self.obj.some_state_2:
t = template.loader.get_template('some_different_html_view.html')
result = 'something'
else:
if self.obj.process_data:
t = template.loader.get_template('some_list_data.html')
result = 'something'
else:
t = template.loader.get_template('no_data.html')
result = 'something'
return t.render(Context({'result': result}, autoescape=context.autoescape))
#register.tag
def process_data(parser, token):
try:
tag_name, arg = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError("%r tag requires arguments" % token.contents.split()[0])
return ProcessData(arg)
Finally, in your template:
{% load my_tags %}
{% process_data data.mymodel %}
You could use jinaj2 for templating that view (or the whole project), it supports if/elif/else branching:
{% if data.some_state %}
Display some markup
{% elif data.some_state_2 %}
State 2 different view
{% elif data.process_data %}
Display some list of data
{% endif %}
There are a couple different packages which it easy use jinja2 in a django project, I've used both coffin and djinja for this.
Though I think #burhan's approach is better, you could also do what you want to do by using a custom tag that sets a context variable to a boolean and than outermost else part could also be converted into a if tag
#Set a context variable nodata to True
{% setnodata True %}
{%if data.some_state %}
Display some markup
#Set context variable nodata to False
{% setnodata False %}
{% endif %}
{%if data.some_state_2 %}
State 2 different view
#Set context variable nodata to False
{% setnodata False %}
{% endif %}
{%if data.process_data %}
Display some list of data
#Set context variable nodata to False
{% setnodata False %}
{% endif %}
{% if nodata %}
No data provided !
{ % endif %}
The setnodata custom tag simply sets the context variable nodata to True or False depending upon the argument.
today I meet the same question.
And I find this tag {% verbatim %} {% endverbatim %} .This works in Django1.5+
An example:
{% verbatim %}
<div class="entry">
<h1>{{ title }}</h1>
<div class="body">
{{ body }}
</div>
</div>
{% endverbatim %}
You can also look below for more details:
https://groups.google.com/forum/#!topic/django-users/-_wBLDuzaNs
Handlebars.js in Django templates