简体   繁体   中英

Creating objects/functions within Jinja to better re-use code

I'm currently working on a practice blog site to learn more about web development and I am using Flask.

On my site, people can create blog posts and view the posts of others. Obviously, I want to make my code as re-usable as possible. So right now, depending on the page, I am grabbing some number of blog posts in my routes.py, and then passing them into a number of different pages (eg home page, profile page, search page).

Each of these pages has its own template since they all look different. However, the code for displaying the blog posts is the same in all of the sites, even though the blog posts themselves may differ. Is there any way in Jinja to create an object or function (eg render_as_blog_posts()) to which I could pass in the blog posts to and run in the template? For example:

routes.py

def profile():
    blog_posts=profile_blog_posts
    return render_template("profile.html",posts=blog_posts)
def search():
    blog_posts=search_blog_posts
    return render_template("search.html",posts=blog_posts)

profile.html:

<html>
<title>Profile</title>
{{ render_as_blog_posts(blog_posts) }}    
</html>

search.html:

<html>
<title>Search</title>
{{ render_as_blog_posts(blog_posts) }}    
</html>

I suppose, you're looking for the 'template inheritance' feature of Jinja2: https://jinja.palletsprojects.com/en/2.10.x/templates/#template-inheritance

Basically, you can achieve what you want in the different ways:

  1. Template extension: https://jinja.palletsprojects.com/en/2.10.x/templates/#base-template In this case you can define base template with common layout, common set of macroses and define special blocks in this template as a points of customization. Then, you can extend this template and fill blocks in the way specific for derived template (see samples by the provided link)
  2. Templates import: https://jinja.palletsprojects.com/en/2.10.x/templates/#import More specific feature which looks like exactly the same python's one. You can define special template which contains set of macros and then import this template into yours profile.html or search.html :

    {% import 'commmon_functions.html' as common %}

    Then you can refer functions from this file as a part of common namespace:

    {{ common.render_as_blog_posts(blog_posts) }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM