Django中被引入的模板文件如何知晓自身已被引入?
Django模板{% include %}的识别与自定义变量方案
- Django没有默认提供供被引入模板识别自身已被包含的变量。
- 完全不需要创建两个模板文件,通过给
{% include %}标签传递自定义变量就能实现需求。
修改后的代码示例
a.html(引入方模板)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>From a.html</h1> <!-- 引入时传递自定义变量,标记当前是被包含状态 --> {% include "b.html" with included_in_file=True %} </body> </html>
b.html(可独立访问/被引入的模板)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <!-- 判断变量是否存在且为True,不存在则视为独立访问 --> {% if included_in_file %} <h1>From b.html</h1> {% else %} <h1>Hello</h1> {% endif %} </body> </html>
补充说明
当b.html被单独访问时,只要视图没有传递included_in_file变量,模板会自动进入else分支,展示独立访问的内容;如果需要更严谨,也可以用{% if included_in_file is defined %}来判断变量是否存在。
内容的提问来源于stack exchange,提问作者Giorgos V
相关产品推荐
相关产品推荐

