1

I'm trying to add variables in python embedded in my HTML and it just prints out the add statements instead of executing them. Here is my code from my html file:

<% x = 0 %>
{% for c in UGC %}
 {% if c.doctor_id == doctor.id %}
 <% {{x}} = {{x}} + {{c.time}} %>
 <h4>Around {{c.time}} minutes.</h4>
 <h4>{{c.comment}}</h4>
 <h4>{{c.submitted_on}}</h4>
 <br>
 {% endif %}
{% endfor %}

{{c.time}} prints out the actual time from the database. {{c.comment}} and {{c.submitted_on}} print out the relevant comment and time stamp from the DB respectively. However, when I initialize x to 0 and then try to add time to it on every iteration of the loop, this is printed: '<% = + 33 %>' where 33 is the value of {{c.time}} for that iteration of the loop.

asked Jun 13, 2014 at 19:04
1
  • 1
    But that's php syntax. What made you think it would work in a Django template? Commented Jun 13, 2014 at 19:06

2 Answers 2

1

1 - You are mixing PHP template and Django template.

2 - if you are using x here as a temporary variable, you can use with tag of template.

{% with x = 0 %}
/// you code here
{% endwith %}

3 - this line <% {{x}} = {{x}} + {{c.time}} %> would never work. You have to write your own template tag in order to add. {% x|add:c.time %}

Maxime Lorant
36.4k19 gold badges91 silver badges97 bronze badges
answered Jun 13, 2014 at 19:24
Sign up to request clarification or add additional context in comments.

Comments

0

For one thing (as Daniel Roseman pointed out), the code you have looks like PHP. The Django templating language is not PHP and shouldn't be used in that way. The kind of logic you have in your template should be restricted to the view, with the templates only being used for rendering the output.

Your view could create a list of dicts and pass that list to your template. Then it could be used like this:

{% for doctor_comment in doctor_comment_list %}
 <h4>Around {{ doctor_comment.time }} minutes.</h4>
 <h4>{{ doctor_comment.comment }}</h4>
 <h4>{{ doctor_comment.submitted_on }}</h4>
{% endfor %}
answered Jun 13, 2014 at 19:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.