[英]NameError: name 'go' is not defined in sublime text 3 console
[英]How to test if a Go template block is defined?
我正在使用帶有內置 HTML 模板引擎的 Go 1.19。 有沒有辦法測試一個塊是否在特定的模板文件中定義?
具體來說,我想在 Go HTML 模板中實現可選的 header 條目。
我有一個通用布局模板,在呈現時包含一個內容模板。
我想實現如下...
目前, <meta name="description" content="{{block "description".}}{{end}}">
導致一個空的描述標簽。 我想根本沒有標簽,里面什么都沒有。
有任何想法嗎?
layout.gohtml(簡體)
<html>
<head>
<title>{{block "title" .}}The Title{{end}}</title>
{{ifblockdefined 'description'}}
<meta name="description" content="{{block "description" .}}{{end}}">
{{end}
</head>
<body>
<header></header>
{{template "content" .}}
<footer></footer>
</body>
</html>
content1.gohtml
{{define "title"}}The 2hO Network{{end}}
{{define "description"}}An options description{{end}}
{{define "content"}}
Vestibulum ante ipsum primis in faucibus...
{{end}}
content2.gohtml
{{define "title"}}The 2hO Network{{end}}
{{define "content"}}
Vestibulum ante ipsum primis in faucibus...
{{end}}
模板被設計為可靜態分析的。 這意味着如果您沒有description
模板,則在解析模板時會出錯。
而是使用{{if}}
操作來檢查是否需要呈現description
模板。 description
模板可能為空。
例如:
{{if .renderDescription}}
{{template "description"}}
{{end}}
{{define "description"}}description content{{end}}
如果你必須在很多地方檢查.renderDescription
,你也可以將檢查( {{if}}
動作)移到模板中,這樣你就可以無條件使用{{template}}
(但你仍然需要提供管道包含條件):
{{template "description" .}}
{{define "description"}}
{{if .renderDescription}}
description content
{{end}}
{{end}}
筆記:
{{block}}
動作不是包含模板,而是定義和包含模板。 要包含在別處定義的模板,請使用{{template}}
。
您還必須更改模板結構。 不要讓“框架”模板嵌入“內容”,而是定義“頁眉”和“頁腳”模板,並讓每個頁面都有自己的模板,包括“頁眉”、內容和“頁腳”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.