当前位置:网站首页>Flask博客实战 - 实现全站导航菜单及首页数据展示
Flask博客实战 - 实现全站导航菜单及首页数据展示
2022-06-22 08:21:00 【轻编程】
Flask上下文处理器
我们博客的设计是全站顶部菜单为通用菜单,调用的数据为文章的分类,那么如何将文章分类数据传递到每个页面的上下文呢?
为了将新变量自动注入模板的上下文中,Flask 中存在上下文处理器context_processor。上下文处理器在呈现模板之前运行,并且能够将新值注入模板上下文。上下文处理器是返回字典的函数。然后,对于应用程序中的所有模板,此字典的键和值将与模板上下文合并:
用法为如下所示,这只是一个例子:
@app.context_processor
def inject_user():
return dict(user=g.user)上面的上下文处理器使一个名为 user 的变量在模板中可用,其值为 g.user。这个例子不是很有趣,因为g无论如何都可以在模板中使用,但它给出了它是如何工作的。
变量不限于值;上下文处理器还可以使函数可用于模板(因为Python允许传递函数):
@app.context_processor
def utility_processor():
def format_price(amount, currency="€"):
return f"{amount:.2f}{currency}"
return dict(format_price=format_price)上面的上下文处理器使format_price函数可用于所有模板:
{
{ format_price(0.33) }}您还可以将fo
边栏推荐
- Optimization of MySQL paging scheme by database and table
- Alibaba cloud ~ simply send SMS
- Using KDJ metrics on MT4
- 找出不是两个数组共有的元素
- How to create an index
- Example of multipoint alarm clock
- Mt4/mql4 getting started to proficient in foreign exchange EA automatic trading tutorial - special identification of the K line on the chart
- Record once · fluent file buffer
- C # realizes voice reading function
- Web knowledge 4 (filter+listener)
猜你喜欢

QT custom composite control (class promotion function)

Thread status (timed wait, lock blocking, infinite wait (key))

Seven challenges faced by CIO in 2022 and Solutions

Record once · fluent file buffer

成为一名卓越云架构师要具备的五项技能

Fastcorrect: speech recognition fast error correction model RTC dev Meetup

Postgresql源码(56)可扩展类型分析ExpandedObject/ExpandedRecord

Five skills to be an outstanding cloud architect

Third party services (file and picture storage)

The solution to the problem of the first screen picture loading flicker
随机推荐
Design skills of common table structure in database design
[Oracle database] mammy tutorial Day11 numerical function
Five skills to be an outstanding cloud architect
Oracle database pl/sql procedure body, cursor, stored procedure
C language implements inserting and reading pictures into MySQL
多点闹钟实例
Develop steam education based on scientific skills
读取jar包里面文件夹下的所有文件
Summary of basic knowledge of Oracle database SQL statement II: data operation language (DML)
The challenge of image based voice processing in real-time audio and video -- RTC dev Meetup
I spring and autumn web Penetration Test Engineer (elementary) learning notes (Chapter 3)
HashTable源码解析、Collections.synchronizedMap解析
steam教育文化传承的必要性
计算天数()
Chapter VIII web project testing (the end of this chapter)
Optimization of MySQL paging scheme by database and table
Define the data source of hikaricp connection pool for bee
Some mathematical operation functions in LabVIEW
Summary of basic knowledge of Oracle database SQL statements I: Data Definition Language (DDL)
同态加密的基本概念