mango
mango

Reputation: 553

How do I insert this python code into my html template?

the python for the get method:

    posts = Post.all().order('num')
    for post in posts:
        key = post.key()
        self.write('<div class = "art"><img src="img?img_id=%s" class = "art" width = "500"></img></div>' % post.key()) 

    self.render("art.html", posts = posts)

art.html:

{% extends "base.html" %}

{% block content %}
<form method="post" class = "art">
    {% for post in posts %}
        <div class = "art_title">{{post.title}}</div>
        <div class = "art_note">{{post.note}}</div>
        <br>
    {% endfor %}
</form>
</div>

{% endblock %}

This works fine for displaying a single post, but when there are more than one posts, all the art is rendered at the top in one giant heap and then the title and description notes are rendered in another heap of words. I want the page to render the art, title, and note together, for a single post.

How would I insert the python for loop with the string substitution into the html? (I also tried inserting the html into the python but the extends "base.html" line messes it up...if I were to do it this way, how would I extend the "base.html"?)

EDIT:

I tried

posts = Post.all().order('num')
self.render("art.html", posts = posts)

and

<div class = "art_box">
<form method="post" class = "art">
    {% for post in posts %}
        <div class="art"><img src="img?img_id={{post.key}}" class="art" width="500"></img></div>
        <div class = "art_title">{{post.title}}</div>
        <div class = "art_note">{{post.note}}</div>
        <br>
    {% endfor %}
</form>
</div>

which didn't display the pictures at all, only the title and the description.

Is there a way I can get the value of post.key in the html and substitute that in the url?

Upvotes: 1

Views: 1332

Answers (1)

kalhartt
kalhartt

Reputation: 4129

Let the template do the work for you, notice your art.html is already looping over posts. All you need to do is add the images to the template. In general your view functions are for retrieving / processing data while your templates are responsible for formatting / displaying.

art.html

...
{% for post in posts %}
    <div class="art"><img src="img?img_={{post.key()}}" class="art" width="500"></img></div>
    <div class="art_title">{{post.title}}</div>
...

The only problem you might run into is that post.key is a callable and not a value of some kind. Most template engines work fine with callables, but in that rare case you might have to build the context yourself.

EDIT:

Since you stated you are using Jinja, method calls must be done explicitly by adding parenthesis to {{post.key()}}

Upvotes: 1

Related Questions