context_processor context processor

context_processor context processor

Blog There are three places to use the tag cloud: the main page, category page, blog details page, so with the following piece of code

# 主页面
@main.route("/") def index(): tags = Tag.query.all() # ...省略部分代码 return render_html("index.html", tags=tags,) # 分类页面 @main.route("tag/<int:id>") def tags(id): tags = Tag.query.all() # ...省略部分代码 return render_html("tags.html", tags=tags,) # 博客详情页面 @main.route("post/<int:id>") def post(id): tags = Tag.query.all() # ...省略部分代码 return render_html("post.html", tags=tags,post=post)

It seems to solve the problem? All pages can be displayed a tag cloud? But these three pages are return tags will not be too difficult to read some, completely elegant Well, there is no good way to do it? The answer naturally is there, next to our focus on the.

context_processor debut

Like we said before the hook function, it also has a brother --app_context_processor, the difference is very simple, which is the blueprint for. Let's look at its official definition:

Registers a template context processor function.

Translation is simple: Register template context processor functions. This can really solve our problem? Do not worry Let's try, before the code transform the look.

@main.app_context_processor
def peach_blog_menu():
    tags = Tag.query.all() return dict(tags=tags) @main.route("/") def index(): # ...省略部分代码 return render_html("index.html") # 分类页面 @main.route("tag/<int:id>") def tags(id): # ...省略部分代码 return render_html("tags.html") # 博客详情页面 @main.route("post/<int:id>") def post(id): tags = Tag.query.all() # ...省略部分代码 return render_html("post.html")

Is not find out what disappeared? tags seem to disappear from several functions before, there is no back to the front desk, access to it? Nature is possible. The reason is naturally context_processor, and it can be our definition of variables visible in all templates.

How to use it?

1. As described above the code, context_processor modified as a function of a decorator

2. The function returns the result must be a  dict , and its  key  will be visible in all variables as a template

 

While many functions in your view needs to return a variable of the same time, this time we can consider the use context_processor

Guess you like

Origin www.cnblogs.com/leijiangtao/p/11790065.html