Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to See if a String Contains Another String in Django Template

Tags:

python

django

This is my code in a template.

{% if 'index.html' in  "{{ request.build_absolute_uri  }}" %}      'hello' {% else %}           'bye' {% endif %} 

Now my url value currently is "http://127.0.0.1:8000/login?next=/index.html"

Even though "index.html" is there in the string it still prints bye.

When I run the same code in a python shell it works. Not sure what the mistake is.

like image 234
curiousguy Avatar asked Oct 28 '13 05:10

curiousguy


People also ask

What does {% %} mean in Django?

{% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.

What does {% include %} do?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.

What is Jinja pattern in Django?

Jinja is similar to the Django template engine but provides Python-like expressions while ensuring that the templates are evaluated in a sandbox. It is a text-based template language and thus can be used to generate any markup as well as source code. Jinja.


1 Answers

Try removing the extra {{...}} tags and the "..." quotes around request.build_absolute_uri, it worked for me.

Since you are already within an {% if %} tag, there is no need to surround request.build_absolute_uri with {{...}} tags.

{% if 'index.html' in request.build_absolute_uri %}     hello {% else %}     bye {% endif %} 

Because of the quotes you are literally searching the string "{{ request.build_absolute_uri }}" and not the evaluated Django tag you intended.

like image 137
Farmer Joe Avatar answered Oct 02 '22 12:10

Farmer Joe