Flask and Jinja for loop skip if file contains errors - python

I'm having a issue where I am trying to display some thumbs. The problem is that when I run the jinja2 with the variable it displays the alt text, I would rather have it skip or pass if the thumb contains errors instead of displaying alt text.
Here is code
{% block content %}
{% if games %}
{% for g in games if g.game_thumb %}
<img src="static{{ g.game_thumb }}" class="img-rounded" alt="{{ g.game_name }}" width="150" height="150">
{%endfor%}
{% endif %}
{% endblock %}

I ended up solving this via the flask route via.
from PIL import Image
try:
Image.open(thumb).verify()
print "image"
except:
print "failed"
continue

Another way and propably more efficient, would be to use image preloading. Pass the src list to javascript through a data attribute or render to a javascript variable. Using javascript you can preload the images and discard the ones that do not load.
You can also simply handle onerror on img which is called when it fails to load, and hide/remove the images.

Related

Django: TemplateSyntaxError-Could not parse the remainder

My template gets a queryset named qs.value sent from the views.py, I can display the value using {{qs.value}} anywhere in the template, but using it in an if statement raises an error.
{% if {{qs.value}} > 0 %}
<!--do something-->
<h3 class="text-success">{{qs.value}}</h3>
{% else %}
<!--do something else-->
<button class="btn btn-primary">Else</button>
{% endif %}
The error:
Could not parse the remainder: '{{qs.value}}' from '{{qs.value}}'
What am I doing wrong?
{{ }} are used to get the string representation of the variable/fuction. {% %} are used to make some code working. Both can read variables/functions as they are passed with context without any additional {{/{% inside them because they process given arguments directly.
This error usually means you've forgotten a closing quote somewhere in the template you're trying to render. For example: {% url 'my_view %} (wrong) instead of {% url 'my_view' %} (correct). In this case it's the colon that's causing the problem. Normally you'd edit the template to use the correct {% url %} syntax.

Nested for loop with if statement in Jinja fails to work

enter image description hereenter code here`
<div class="container">
{% for bookmark_title in bookmarks_titles %}
<div class="container-head">
<h2>{{ bookmark_title.title }}</h2>
<span>{{bookmark_title.description}}</span>
</div>
{% for bookmark in bookmarks %}
{% if bookmark.tag == bookmark_title.title %}
<div class="container-body">
<img src="{{bookmark.favicon}}" alt="icon" /> {{ bookmark["title"]}}
</div>
{% endif %}
{% endfor %}
{% endfor %}
</div>
When I run the HTML the first for loop works as expected however, the second nested for loop and if statement only runs after the parent for loop ends.
But I want to return the "Bookmark" saved under each Bookmark_title.title.
As you can see in the attached image for nested for loop works only after the parent for loop ends.
Any suggestion, please.
In the process of filtering all the bookmarks before passing them to the HTML page. Instead of appending the filtered data from the database.db I was replacing with the new results so only the bookmarks, I filtered using the last title tag in this case Entertainment only passed into the HTML page which caused the issue.
To fix it I filtered all the bookmarks from the database.db since the 'Bookmarks' sheet only has the bookmarks, so I don't need to filter by tag.)
# Previously
for tag in tags:
bookmarks = db.session.query(Bookmarks).filter_by(tag=tag)
Fix
bookmarks = db.session.query(Bookmarks).all()

How to fix Python template tags for calling variables in HTML page, like {{ my_name }}

I created a variable in my python script. I want to display the value of this variable on my page. So I passed the variable to a dictionary and call the key on my HTML file. However, when I refresh my page it does not show any error and yet the value too does not show.
I am new to python, I do not know what the problem could be. Please is there any way to enable this template tag {{ }} before use?
Like so: Python function
from django.shortcuts import render
def about(request):
my_name = 'Hello! My name is Andi#ITech'
return render(request, 'about.html', {"my_name":my_name})
HTML File
{% extends 'base.html' %}
{% block title %} About Andi#ITech {% endblock %}
{% block content%}
Home | About
<br><br>
<em>About Me</em>
<br>
{% if 2 > 21 %}
Halo!
{% else %}
GOODBYE
{% endif %}
<br>
{{ my_name }} <-- this line of code does not show anything -->
{% endblock %}
I expected the following sentence to display on my page
: Hello! My name is Andi#ITech.
The syntax looks good to me. Are you sure your block is executing correctly? It is enough that there is typo in the name of the base block (like contetn) and the block in the about.html file is not executed. It is also possible that the block is correctly executed but there is an error in the HTML and the browser does not show the text because it is inside a tag. Did you check the HTML resulting code? Also CSS can hide your text... It is not easy to give you a precise answer without all the code.

Do statement not working in jinja

I'm altering an existing web interface to view ROBOT doc libraries, which uses a mixture of jinja (Python inside HTML) and HTML. I have never worked with jinja or HTML before and am having issues getting even a simple test case to work. When the browser loads the docs, I want our project's directory structure for the docs to be preserved to make finding things easier, and so I want to use jinja to create the dir structure. Here is a snippet of the code I'm working with:
{% extends "base.html" %}
{% block body %}
<div class="well" id="left">
<ul class="list-group list-unstyled">
{% set collection_list = [] %}
{% for collection in data.hierarchy %}
{% if collection.collection_id|string == data.collection_id|string %}
{% do collection_list.append(collection.path) %}
{% else %}
{% for link in collection.path_chain %}
<li>
<label class="tree-toggler nav-header"
title="file path: {{collection.path}}">{{link}}</label>
<ul class="list-group tree collapse"
id={{link}}>
</ul>
{% endfor %}
</li>
{% endif %}
...there's more after that, but this is where I hit the error. It sets the collection_list var fine, and the if statements work, but when it goes to execute the 'do' statement it fails with:
TemplateSyntaxError: Encountered unknown tag 'do'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.
I don't believe this is an unclosed loop or something because if I replace the do statement with a simple test print statement, it works. Does anyone know what I'm doing wrong?
From the template documentation:
Expression Statement
If the expression-statement extension is loaded, a tag called do is available that works exactly like the regular variable expression ({{ ... }}); except it doesn’t print anything. This can be used to modify lists:
{% do navigation.append('a string') %}
You need to enable the Expression statement extension for this to work.
You didn't show how you load the Jinja2 environment, but loading extensions takes place via the extensions argument to the Environment() class:
jinja_env = Environment(extensions=['jinja2.ext.do'])

load static file with variable name in django

I'm trying to do load the following static file
img file
where image is in a for loop of images derived from a database.
But I simply got an error Could not parse the remainder: '{{' from ''static/matrices/'{{'
What should I do to fix this? I can't use relative paths because this will be used by subsections as well, with the same html template.
You should pass a full string to the static tag from staticfiles. This is so it can use your staticstorages to find your file.
{% load staticfiles %}
{% with 'images/'|add:image.title|add:'.png' as image_static %}
{% static image_static %}
{% endwith %}
But in your use case it might be better if you just store the path of the images on the image model itself.
I got this to work by using an empty string for the static path and then using my variables in their own section, like this:
<a href= "{% static "" %}{{obj.a}}/{{obj.b}}/{{obj.c}}.gz" >Name</a>
You can use get_static_prefix template tag. get_static_prefix is a variable that contains the path specified in your STATIC_URL. Your code would be:
{% load static %}
img file
or
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
img file
Reference: get_static_prefix
You should avoid nesting tags.
What are you trying to solve? Isn't the image part of dynamic content? The static tag is for static content not uploaded media files.
If you must use the static tag the correct way would be something in the order of;
{% static image %} or {% static image.file %}
Depending on the object layout. If you're using an ImageField (inherits FileField) the image object already holds the path, so there's no need to manually add extensions.
What I ended up doing was to just split the path from the name itself. Those images represents tabs, are static and in a sequence. They are not connected to the database imagewise.
I didn´t want to repeat the html for every run so I ended up doing a forloop like this, a bit simplified.
{% for option in options_obj %}
<img class="highlight" src="{% static "store/img/editor/tab-" %}
{{ option.name.lower }}-selected.png">
{% endfor %}
EDIT:
Even though this does work in most situations it can really mess stuff up as well. For me this occured when having different images for different language settings and at the same time using tools like CachedStaticFilesStorage. If you need to add language code or something else to your image this is a more solid solution
{% for option in options_obj %}
<img class="highlight" src="{% static "store/img/editor/tab-"
|add:LANGUAGE_CODE|add:"-selected.png" %}">
{% endfor %}
Too many quotes!
Just
img file
and you don't have to call the static in the link because you already load the static

Categories

Resources