How do you declare python variables within flask templates? - python

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.

Related

Flask's Jinja nesting some rendered elements in 'strong' elements

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

Could not parse the remainder: '{{ list[loop.index0] }}'

I followed instructions in simmilar thread like: How do you index on a jinja template?
but my html template is not working and whole django project is not responding due to this.
Error that I'm getting:
Error during template rendering.
Could not parse the remainder: '[loop.index0]' from 'songs_titles[loop.index0]'
My code looks like this:
{% if converted_files_urls %}
<p>Titles: {{ songs_titles }}</p>
{% for n in converted_files_urls %}
<a href="{{ n }}" download>Download: {{ songs_titles[loop.index0] }}</a>
<br/>
{% endfor %}
{% endif %}
and the {{ songs_titles }} renders as list, so at least till here it works ok.
What am I doing wrong?
Actually you are looking for Jinja, that will not work on django.
In django template tag you should use forloop.counter0 and list indexing looks like
{{songs_titles.1}}
Need to set count in variable and then use it, for setting variable you could use -
{% with index=forloop.counter0 %}
{{ songs_titles.index}}
{% endwith %}
Still If you have any doubts you can comment it.
I finally resolved this by creating a custom template tag like here:
https://djangosnippets.org/snippets/2740/
But to be honest it sucks that that's the simplest working solution for now :/

Pelican -- 'articles_page' is undefined

I've created my own theme for Pelican and I've been using it for a while to build my site. I've decided to start blogging again so I'm only now adding the blog features to the site.
I've created my own blog.html template to render the content in the way I want. I started by copying and pasting the code from the 'simple' theme that comes with Pelican to get me started, but even though it is unchanged I'm getting an 'articles_page' is undefined error when I try to build.
Where is the article_page variable set from? I tried adding to my pelicanconf.py file but it didn't help.
{% extends 'base.html' %}
{% block title %}{{ page.title }} — Ricky White{% endblock title %}
{% block content %}
<section class="wrapper">
<div class="container">
<div class="row">
<div class="col">
<ol id="post-list">
{% for article in articles_page.object_list %}
<li><article class="hentry">
<header> <h2 class="entry-title">{{ article.title }}</h2> </header>
<footer class="post-info">
<time class="published" datetime="{{ article.date.isoformat() }}"> {{ article.locale_date }} </time>
<address class="vcard author">By
{% for author in article.authors %}
<a class="url fn" href="{{ SITEURL }}/{{ author.url }}">{{ author }}</a>
{% endfor %}
</address>
</footer><!-- /.post-info -->
<div class="entry-content"> {{ article.summary }} </div><!-- /.entry-content -->
</article></li>
{% endfor %}
</ol><!-- /#posts-list -->
{% if articles_page.has_other_pages() %}
{% include 'pagination.html' %}
{% endif %}
</div>
</div>
</div>
</section>
{% endblock content %}
You must have referenced your template from one of the articles using:
Template: blog
If you remove that reference and add the following lines to your pelicanconf.py, Pelican will generate blog.html directly from your template file:
DIRECT_TEMPLATES = ['index', 'blog']
PAGINATED_DIRECT_TEMPLATES = ['blog']
(Do not forget to empty your output folder before running pelican. Tested on Pelican 3.7.1)
For the sake of future visitors who might come here looking for an answer like I did:
The problem can have a good number of very diverse reasons. In my case it was not a problem with the configuration of the pelican tooling, but rather an error in the metadata of some of my content pages. I had not included the correct category, date or tag fields. You'd never guess that from the error message now, would you?
I found this question looking for the same error.
In my case the reason was an issue which has been closed but not merged in the current release of the Attila theme. More precisely: the error is caused by a template in the templates folder of the theme which has a wrong reference inside it. In the specific case, inside the page template there was a wrong reference to article.
Changing the template manually fixed the issue:
--- a/attila-1.3/templates/page.html
+++ b/attila-1.3/templates/page.html
## -21,8 +21,8 ##
{% else %}
{% set selected_cover = SITEURL+"/"+HEADER_COVER %}
{% endif %}
-{% elif article.color %}
- {% set selected_color = article.color %}
+{% elif page.color %}
+ {% set selected_color = page.color %}
{% elif HEADER_COLOR %}
{% set selected_color = HEADER_COLOR %}
{% endif %}
I hope this helps debugging similar errors.
The page variable articles_page is set in only one place: Writer._get_localcontext and there is a guard condition:
if paginated and template_name in self.settings['PAGINATED_TEMPLATES']:
# ... code ...
paginated_kwargs.update(
{'%s_paginator' % key: paginator,
'%s_page' % key: page, # <-- Creates `article_page`
'%s_previous_page' % key: previous_page,
'%s_next_page' % key: next_page})
If this problem crops up, the easiest solution is to make sure the guard condition evaluates to True. Most likely, the problem is that template_name is not in PAGINATED_TEMPLATES in your configuration file. I opened writers.py, added a print(f"template_name is {template_name}") and got my answer (I didn't have author : None in my PAGINATED_TEMPLATES dictionary).

what does {% random code here %} means in HTML file

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/.

how to create counter loop in django template?

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.

Categories