twig - 如何检查 OctoberCMS 布局模板中是否存在页面属性
问题描述
is defined
在布局中,当页面未定义属性时,检查页面属性会产生类似“调用未定义方法 October\Rain\Halcyon\Builder::meta_description()”的错误。我希望测试是假的,而不是抛出异常。
我有如下检查的布局if this.page.meta_description is defined
。
description = "Default layout"
==
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ this.page.title }}</title>
{% if this.page.meta_description is defined and this.page.meta_description is not empty %}
<meta name="description" content="{{ this.page.meta_description }}">
{% endif %}
</head>
<body>
...
</body>
</html>
如果使用此布局的页面定义了meta_description
属性,则它呈现得很好。但是,如果页面没有定义它,this.page.meta_description is defined
部分会抛出异常。
检查页面属性是否已定义的正确方法是什么?
解决方案
我刚刚找到了一种通过关联数组语法访问属性来解决这种情况的方法。
{% if this.page['meta_description'] is defined and this.page['meta_description'] is not empty %}
<meta name="description" content="{{ this.page.meta_description }}">
{% endif %}
这按我的预期工作,但是,我不确定这是否是最好的解决方案。
推荐阅读
- python - 在 Python 中使用 iCloud 发送电子邮件
- r - 如何解决线性回归时间序列分析中的“attr(data, "tsp") <- c(start, end, frequency) 中的错误:对象不是矩阵”?
- gpu - 在 IMX8 上测量 Vivante G7200L 的 FLOPS
- c# - 如何从 Gremlin.NET 批量向 gremlin 服务器添加顶点?
- mysql - 删除触发器之前的 msql 5.0 - 取消
- r - 根据基于 grepl 的查询中的变量总和创建具有 mutate 的列
- c# - 使用 LUIS 进行对话中断的最佳做法是什么
- azure-web-app-service - ASP.NET Core 2.2 的 Azure 应用服务标准输出为空
- python-3.x - 通过“os.system”创建的文件名中的问号
- c++ - 除非我添加 __declspec(dllimport) 否则链接错误