pimoroni / phew

MIT License
204 stars 44 forks source link

is it possible looping in templates? #28

Closed lixas closed 1 year ago

lixas commented 1 year ago

Hello I'm building system based on Phew and I would like to know, is there a way to render page using some kind of looping

What i do have

data = [
{"name": "Jack", "url": "http://exaple.com"},
{"name": "Johan", "url": "http://blog.johan.com"},
{"name": "Marry", "url": "http://facebook.com/marry"},
... etc
]

Is there a way dynamically build list of links with predefined template?

<ul>
{{loop data}}
    <li><a href="{{url}}" class="person">Page for {{name}}</a></li>
{{endloop}}
</ul>

This is just a presentation of my idea what I want to achieve. Keep in mind that array of data is not fixed length and I cannot prepare static number of li tags.

lixas commented 1 year ago

Solved my issue, when I saw that I can use inline python syntax. Not most elegant solution, but it works well

@server.route("/template", methods=["GET"])
async def templates(request):
    data = [
        {"name": "Jack", "url": "http://exaple.com"},
        {"name": "Johan", "url": "http://blog.johan.com"},
        {"name": "Marry", "url": "http://facebook.com/marry"}
    ]

    return await render_template("themes/basic/list.html", data_placeholder=data)

list.html template file

<html>
    <title>List example</title>
    <body>
        List of links for users
        <ul>
{{
"".join(["""<li>
    <a href=\"{1}\" class=\"person\">Page for {0}</a>
</li>\n""".format(itm["name"], itm["url"]) for itm in data_placeholder])
}}
        </ul>
    </body>
</html>

And the final result is exactly what i've expected

<html>
    <title>List example</title>
    <body>
        List of links for users
        <ul>
<li>
    <a href="http://exaple.com/" class="person">Page for Jack</a>
</li>
<li>
    <a href="http://blog.johan.com/" class="person">Page for Johan</a>
</li>
<li>
    <a href="http://facebook.com/marry" class="person">Page for Marry</a>
</li>
        </ul>
    </body>
</html>
simonprickett commented 10 months ago

This should be made clearer in the documentation.