How to resolve Templatesyntaxerror in Django?

Asked

Viewed 28 times

-1

This is my code snippet, and as you can see, I close the block at the end, but I keep getting the bug

{% extends "encyclopedia/layout.html" %}

{% block title %}
    Edit page
{% endblock %}

{% block body %}
        <form>
            <label for="title">Title:</label>
            <input type="text" class="form-control" id="title" placeholder="Title of the page">
            <label for="textArea">Page content:</label>
            <!--ERRO AQUI-->
            <textarea class="form-control" id="textArea" rows="15">         
                {% print(f"teste") %}   
            </textarea>
            <br>
            <button type="button" class="btn btn-primary">Post!</button>
        </form>
{% endblock %}

Error:

TemplateSyntaxError at /editPage
Invalid block tag on line 14: 'print(f"teste")', expected 'endblock'. Did you forget to register or load this tag?
TemplateSyntaxError at /editPage
Invalid block tag on line 14: 'print(f"teste")', expected 'endblock'. Did you forget to register or load this tag?

1 answer

1

To resolve this error remove the line that has the text:

{% print(f"teste") %}

If you want to print values inside your template the correct way is to put the values between two keys ({{ 'valor' }}).

Follow an example using your code:

{% extends "encyclopedia/layout.html" %}

{% block title %}
    Edit page
{% endblock %}

{% block body %}
        <form>
            <label for="title">Title:</label>
            <input type="text" class="form-control" id="title" placeholder="Title of the page">
            <label for="textArea">Page content:</label>
            <textarea class="form-control" id="textArea" rows="15">         
                {{ 'teste' }}   
            </textarea>
            <br>
            <button type="button" class="btn btn-primary">Post!</button>
        </form>
{% endblock %}

jinja2 (which is the template language of Django) says that to define blocks the syntax is used:

{% block %}
{% endblock %}

Assuming that the variable users is a list in python, we could iterate on the values of this list as follows:

<title>{% block title %}{% endblock %}</title>
<ul>
{% for user in users %}
  <li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>

But to print the values and variables (from python) you must use double keys.

Follow a link to learn more about Jinja2.

  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.