Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

link_to and form_tag macros

Posted by LeafStorm on 2010-05-07 @ 22:36 and 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 () }}
{%- 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.