Reputation: 989
Is there something like .net MVC 3's partial view in flask?
I want to embed a widget in one view page,and that widget has its own logic.
Upvotes: 23
Views: 11652
Reputation: 159855
There are several ways to include content in a Jinja2 template:
The include
statement will render the supplied view (with the current context by default):
{# In your_view_template.jinja #}
{# ... your code ... #}
{% include "widgets/your_widget.jinja" %}
{# ... your code ... #}
You can also define macros and import them into the view template:
{# In your_view_template.jinja #}
{% import "widgets/your_widget.jinja" as your_widget %}
{# ... your code ... #}
{{ you_widget.render(your, important, variables, etc.) }}
{# ... your code ... #}
Both import
and include
can use variables, so something like this is possible:
# In your view
if complex_conditions.are_true():
widget = "widgets/special_custom_widget.jinja"
else:
widget = "widgets/boring_widget.jinja"
render_template("your_view.jinja", widget=widget)
{# In your_view_template.jinja #}
{% include widget %}
{#
import widget as sidebar_widget
{{ sidebar_widget.render() }}
would also work
#}
These both work similarly to MVC's partial views (at least, inasmuch as I understand them)
Alternately, if your widget needs access to ACLs or information that should not be available to the template layer and you cannot re-write your view to take advantage of include
and import
you can take @[Alex Morega]'s suggestion and pass in a callable as a variable to the template and render it there.
# In your view
render_template("your_view.jinja", widget=you_callable, etc, etc, etc)
{# In your_view_template.jinja #}
{# ... your code ... #}
{{ widget() }}
{# Or, if you are returning HTML that is not a Markup construct #}
{{ widget() | safe }}
{# ... your code ... #}
You could even create your own template loader and load different templates depending on almost anything. But that would definitely be overkill for this case.
Upvotes: 30