can any tell me how can I write below code of c in django
for(c=0; c<5; c++)
//do something
i had tried below code but it gives me an error
{% for(c=0; c<5; c++)%}
<div class="tab-content">
<h1 class="tab" title="title for page 1">Page 1</h1>
<p>This is the content of tab 1 on container 1</p>
</div>
{% endfor %}
When you render your template, you may pass range
render_to_response('template_x.html', {'range5': range(5)})
And in html template, probably like this
{% for i in range5 %}
<div class="tab-content">
<h1 class="tab" title="title for page {{i}}">Page {{i}}</h1>
<p>This is the content of tab {{i}} on container {{i}}</p>
</div>
{% endfor %}
I guess you are not good at searching, right (:
A good documentation for a good framework... On the other hand, why you ask for a c-like loop structure in a framework written for python is another question
EDIT: For loop in django templates iterates through an array (or list in python terms). So you have to have a list to iterate.. In your related view, lets say yopu have a number list
number_list = [1,2,3,4,5]
if you pass this list to the template with the same name, then you can iterate through it with
{%for num in nuber_list%}
Number is : {{num}}
{%endfor%}
But as i said, you have to pass that list to template in the return statement line that returns an httpresponse or render your contect to your template as it described in here
I was curious and found a way to do this. Disclaimer: I consider the following code to be WRONG:
{% for i in "abcde" %} do something {% endfor %}
Replace "abcde" with a string of the range you want.
Related
With this code:
{% for o in [1,2,3] %}
<div class="{% cycle 'row1' 'row2' %}">
{% cycle 'row1' 'row2' %}
</div>
{% endfor %}
I get a TemplateSyntaxError:
Could not parse the remainder: '[1,2,3]' from '[1,2,3]'
Is there a way of building a list in a template?
We can use split method on str object :
page.html :
{% with '1 2 3' as list %}
{% for i in list.split %}
{{ i }}<br>
{% endfor %}
{% endwith %}
Results :
1
2
3
You can do it via cunning use of the make_list filter, but it's probably a bad idea:
{% for o in "123"|make_list %}
<div class="{% cycle 'row1' 'row2' %}">
{% cycle 'row1' 'row2' %}
</div>
{% endfor %}
p.s. You don't seem to be using o anywhere, so I'm not sure what you're trying to do.
I made this template tag to achieve this goal.
from django import template
register = template.Library()
# use #register.assignment_tag
# only when you're working with django version lower than 1.9
#register.simple_tag
def to_list(*args):
return args
to use it in template:
{% load your_template_tag_file %}
{% to_list 1 2 3 4 5 "yes" as my_list %}
{% for i in my_list %}
{{ i }}
{% endfor %}
Reference here:
Django simple tags
The other answers here look like the ticket (at least for what I wanted), so I'll provide an answer as to WHY you might want to do something like this (and perhaps there's a better answer for my case than what's been provided):
I came across this question looking for a way to build 3 very similar, but not identical buttons using Bootstrap. One button might look like
<div class="btn-group">
<a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#">
Modality
<span class="caret"></span>
</a>
<ul class="dropdown-menu" id="Modality">
<li>Action</li>
</ul>
</div>
where the difference between buttons is limited to the text of the button (Modality, on its own line above) and the contents of the pertaining to the button, which we'll assume is filled dynamically by JS (referencing id="Modality").
If I need to make 10 of these, copy/pasting the HTML seems dumb and tedious, especially if I want to change anything about my button after the fact (like making all of them split-drop-downs) and it goes against DRY.
So, instead, in the template I could do something like
{% with 'Modality Otherbutton Thirdbutton' as list %}
{% for i in list.split %}
<!-- copy/paste above code with Modality replaced by {{ i }} -->
{% endfor %}
{% endwith %}
Now, granted, in this particular case the buttons add functionality to some related data grid, so the button names could be dynamically filled from django model-sourced data as well, but I'm not at that stage in my design right now, and you can see where this sort of functionality is desirable to maintain DRY.
The simplest is to do
{% for x in "123" %}
drodger is correct, you can't do that in the deliberately-crippled Django template lanuage. Either pass in the list as a context variable when you invoke the template or try a template tag like expr. Then you can say {% expr [1,2,3] as my_list %} and then use my_list in your for loop.
This maybe an inspiration. Use the buildin filter add.
{{ first|add:second }}
first is [1, 2, 3] and second is [4, 5, 6], then the output will be [1, 2, 3, 4, 5, 6].
This filter will first try to coerce both values to integers.
If this fails, it'll attempt to add the values together anyway.
This will work on some data types (strings, list, etc.) and fail on others.
If it fails, the result will be an empty string.
The official specification,https://docs.djangoproject.com/zh-hans/2.0/ref/templates/builtins/#built-in-filter-reference
I'm experiencing a weird behavior with Jinja. I made a dynamic flask route and so I made a jinja modular template, it's just a for loop to create an element for each article present in some data (in a dict) I give to Jinja, the template looks like this :
{% for theme in article_data %}
{% for article in theme["article"] %}
{% if article["main"] == 1 %}
<div style="background-image: url('{{article['content']['image1']}}');" class="theme-item-bg frow space-between">
{% endif %}
{% endfor %}
<div class="wrapper-row space-between pinkfilter">
<div class="uB theme-item-text">{{theme["name"]}}</div>
<div class="pageChanger waves-effect waves-light btn uL primaryB" page="/nos-articles/{{theme['name']}}" title="{{theme['name']}}">Voir plus d'articles</div>
</div>
</div>
{% endfor %}
It does work correctly for most of my pages but for one, it have a really weird behavior, Jinja render one of the article correctly and nest the others in a strong element.
The data used to render the page have the same structure and is correctly parsed.
Is there a way to prevent Jinja from nesting stuff in a strongelement?
There must be either some html inside theme["name"] (fix it by escaping it with theme["name"]|escape), or a <strong> tag not closed in one your templates.
Jinja doesn’t insert random html tags, but the browsers do when trying to parse and fix a broken html code
I was given an assignment and I came across this line of code in one of HTML file of problem set. What does {% random code here %} means in HTML, is it a comment or what? I tried google but could not find it.
one TODO looks like this:
{% extends "layout.html" %}
{% block body %}
<div class="col">
<form action="/compare" enctype="multipart/form-data" method="post">
<!-- TODO -->
</form>
</div>
{% endblock %}
So please sort it out what it is for me ?
It is probably some kind of templating, for example:
http://jinja.pocoo.org/
This means that the {% random code here %} is meant to be filled out by a webserver before returning proper HTML.
{} is an object. Most likely this is part of a template that will process some code from a backend language or javascript. Take a look at mustache which utilizes this syntax https://mustache.github.io/.
I've got some basic experience building websites using a LAMP stack. I've also got some experience with data processing using Python. I'm trying to get a grip on the mongodb-flask-python thing, so I fired everything up using this boilerplate: https://github.com/hansonkd/FlaskBootstrapSecurity
All is well.
To experiment, I tried declaring a variable and printing it...
I get this error message:
TemplateSyntaxError: Encountered unknown tag 'x'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.
Here's my main index.html page
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="col-xs-12">
Hello World, at {{ now }}, {{ now|time_ago }}
</div>
</div>
<div class="row-center">
<div class="col">
{% x = [0,1,2,3,4,5] %}
{% for number in x}
<li> {% print(number) %}
{% endfor %}
</div>
</div>
{% endblock %}
I love learning new things, but man, can I ever get hung up for hours on the simplest of things... any help would be greatly appreciated!!!
Flask uses Jinja as its default templating engine.
The templating language is python-esque, but is not python. This is different from something like a phtml file, which is php interspersed with html.
Check the jinja documentation for more of what you can do, but here's how you set a variable within a template:
{% set x = [0,1,2,3,4,5] %}
http://jinja.pocoo.org/docs/2.9/templates/#assignments
Try this:
{% set x = [0,1,2,3,4,5] %}
See Jinja docs.
I have an HTML page displaying a database populated by emails. I have them displayed in a collapsible, and for each post the timestamp of it is what toggles it and the innards are the email itself. The HTML page is structured like this:
{% extends "base.html" %}
{% block content %}
{% for email in emails %}
<div><button class="btn" data-toggle="collapse" data-target="#demo">{{ email.timestamp }}</button>
<div id="demo" class="collapse">
{{ email.body }}
</div>
{% endfor %}
{% endblock %}
relevant portion of views.py
#app.route('/cruz')
def cruz():
u = Politician.query.get(1)
emails = u.emails.all()
return render_template('cruz.html',title='Ted Cruz',emails=emails)
which produces a webpage that looks like this: http://imgur.com/noqC40E
The problem is that no matter which of those timestamps I click, only the first collapsible opens and closes. I've tried a number of things to fix it, mostly messing around with the HTML page and the for blocks and where I place the {{ email.body }}, but nothing I do seems to work. Can anyone see where this is going wrong?
You are generating the same id attribute for your div each time:
<div id="demo" class="collapse">
You almost certainly need to generate unique ids. You could generate unique ids by adding the loop index perhaps:
<div id="demo-{{loop.index}}" class="collapse">