Flask Snippets

link_to and form_tag macros

By LeafStorm filed in Template Tricks

The HTML/Jinja for a link to a page on your site looks quite awkward.

<a href="{{ url_for('some.view', foo='bar') }}">Link text!</a>

With this macro:

{% macro link_to(endpoint, text) -%}
<a href="{{ url_for(endpoint, **kwargs) }}">{{ text|safe }}</a>
{%- endmacro %}

The above link will become:

{{ link_to('some.view', "Link text!", foo=bar) }}

It's shorter and looks cleaner, especially if the content of the link is also a variable.

A similar technique, using the call tag, can be used for forms:

{% macro form_tag(endpoint, method='post') -%}
<form action="{{ url_for(endpoint, **kwargs) }}" 
      method="{{ method }}">
  {{ caller () }}
</form>
{%- endmacro %}

Then, you can create a form with:

{% call form_tag('create_entry') %}
<p><input type=text name=whatever></p>

<p><input type=submit value=Submit></p>
{% endcall %}

You can put these in a file called _helpers.html, or something similar.

This snippet by LeafStorm can be used freely for anything you like. Consider it public domain.

Comments