首页 > 其他分享 >3_hugo模板框架

3_hugo模板框架

时间:2022-10-22 11:02:46浏览次数:85  
标签:end 框架 hugo Site range html Params 模板

3_介绍hugo的模板

  • hugo 使用go的html/template 和text/templete 库为基础进行模板操作

下面只是基础的go template操作,为了更深度的了解请看 go文档

  • go 模板提供了一种非常简单的模板语言,他坚信只有最基本的逻辑才是属于模板和视图层。

基本语法

go 模板是html文件,加上一些变量和函数,变量和函数使用 {{ }} 获取。

{{ .Title }}
{{ $address }}

函数的参数使用 空格分隔 ,像这样

{{ function arg1 arg2 }}
  • 方法和字段通过点号访问
{{ .Params.bar }}
  • 圆括号可以分组
{{if or (isset .Params "alt") (isset .Params "caption")}} Catption {{end}}
  • 一条语句能拆成多行
{{ if or 
  (isset .Params "alt") 
  (isset .Params "caption")
}}
  • 原始字符串可以包含换行
{{ $msg := `Line one 
Line two. `}}

变量- variable

  • 每个go模板都有一个data对象, 在hugo中,每个模板传递一个页面,在下面的例子中, .Title 是

    可以访问的page 变量中的一个。

  • 因为页面的默认范围就是整个模板, 所以Title元素可以用.Title 访问。

<title> {{.Title }} </title>
  • 变量也可以存储自定义变量,在后续被提及到。
{{ $address := "123 main st." }}
{{ $address }}

hugo 在v0.47以及更老的版本,if条件中被定义的变量

hugo 在v0.48以后的版本,可以用=号重新定义

{{ $var := "hello "}}
{{ if .IsHome }}
	{{ $var = "wolrd"}}
{{end}}
var is {{$var}}

函数- functions

  • go模板只附带了一部分基本的函数,但是也提供了一种机制来扩展原始集。
  • hugo模板函数提供了额外的功能函数明确用户构建网站, 函数调用方法是函数名 空格加参数。
  • 如果不重新编译hugo,就不能增加模板函数。

includes

  • 当需要包含一个模板时, 需要传递他需要的数据

partial

  • 这个函数是用来include partial模板

  • {{ partial 'header.html' .}}
    

Template

  • 这个函数也是包含partial模板,是应用于更老的hugo版本。现在更多地用于调用内部模板。

  • 语法

  • 	{{ templete "_internal/hello.html" .}}
    

迭代 iteration

  • go 模板使用 range 来迭代map、array、slice等

  • {{ range $array }}
    	{{.}}  
    {{end}}
    
  • {{ range $elem_val := $array }}
    	{{ $ele_val }}
    {{end}}
    
  • {{ range $ele_index, $elem_val := $array }}
    	{{ $elem_index }} -- {{ $elem_val }}
    {{end}}
    
  • 如果map, array,slice长度为0, 则range时条件为假, 会走到else分支。

Conditionals

  • If、else、with、or、and 、not 构建了go模板操作的逻辑框架。
  • Range、if 、with 都是以 {{end}}来结束的。
  • go 模板对于以下值认为是false: false(boolean)、0、zero-length的map、slice、string、array

with

  • 如果条件值不存在,或者为false,则跳过次block
{{ with .Params.title }}
	<h4> {{.}} </h4>
{{end}}

hugo-single模板

如果在markdown前面指定了type和layout,会优先选择顺序,一般使用single.html

/layouts/TYPE-or-SECTION/LAYOUT.html
/layouts/TYPE-or-SECTION/single.html
/layouts/_default/single.html
/themes/THEME/layouts/TYPE-or-SECTION/LAYOUT.html
/themes/THEME/layouts/TYPE-or-SECTION/single.html
/themes/THEME/layouts/_default/single.html

list 模板

如果是content目录下的子目录,则比如post目录

访问 http://localhost:1313/post/ , 则会渲染list.html 模板

post就是section类型的页面

模板嵌套规则

hugo引入了partial, template 只用来引入内部模板

如果用define 定义了模板名字,则子模板会输出到baseof.html 中block部分。

hugo会先找到需要解析的模板,比如single.html .如果开头有define 定义的模板名字,则将这个模板输出到baseof.html 中,放入block的位置。

baseof.html 相当于是顶级模板。

with

with 是关键词 重新设置上下文

{{with pipeline}} T1 {{end}}
如果pipeline的值为空, 点`.`的值不受影响,不输出任何结果
否则点`.`的值设置成pipeline的值, 输出T1

{{with pipeline}} T1 {{else}} T0 {{end}}
如果pipeline的值为空, 点`.`的值不受影响,输出T1
否则点`.`的值设置成pipeline的值, 输出T0

define

{{define "name"}} T1 {{end}}
定义一个特定名称的模板

template

{{template "name"}}
引入指定名称的模板, 不传入任何数据.

{{template "name" pipeline}}
引入指定名称的模板, 设置模板上下文点`.`的值为pipeline的值

block

{{block "name" pipeline}} T1 {{end}}
定义特定名称的模板, 并在当前位置引入该名称的模板, 模板的上下文点`.`的值为pipline的值, 
如果该名称的模板未实现(不存在), 则输出T1
就相当于在基础模板页中定义了一个子模板占位符.

循环

{{range pipeline}} T1 {{end}}
pipeline的值必须是数组, 切片, map, channel. 
如果pipeline的长度为0则不会输出任何结果. 否则设置点`.`为数组, 切片, map的遍历值, 输出T1.

条件

{{if pipeline}} T1 {{end}} 
如果pipeline为空则不会输出任何结果, 否则输出T1.
下面这些情况pipeline的值为空, false, 0, 值为nil的指针或接口, 长度为0的数组, 切片, map和字符串

{{if pipeline}} T1 {{else}} T0 {{end}}
如果不为空则输出T1, 否则输出T0

{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}

模板

├── layouts
└── themes
    └── mytheme
        └── layouts
            ├── 404.html             // 404页面模板
            ├── _default
            │   ├── baseof.html      // 默认的基础模板页, 使用的方式是'拼接', 而不是'继承'.
            │   ├── list.html        // 列表模板  
            │   └── single.html      // 单页模板
            ├── index.html           // 首页模板
            └── partials             // 局部模板, 通过partial引入
                ├── footer.html
                ├── header.html
                └── head.html       

content和URL的关系

└── content
    ├── _index.md          // [home]            <- https://example.com/ **
    ├── about.md           // [page]            <- https://example.com/about/
    ├── posts               
    |   ├── _index.md      // [section]         <- https://example.com/posts/ **         
    |   ├── firstpost.md   // [page]            <- https://example.com/posts/firstpost/
    |   ├── happy           
    |   |   ├── _index.md  // [section]         <- https://example.com/posts/happy/ **
    |   |   └── ness.md    // [page]            <- https://example.com/posts/happy/ness/
    |   └── secondpost.md  // [page]            <- https://example.com/posts/secondpost/
    └── quote   
        ├── _index.md      // [section]         <- https://example.com/quote/ **           
        ├── first.md       // [page]            <- https://example.com/quote/first/
        └── second.md      // [page]            <- https://example.com/quote/second/

// hugo默认生成的页面, 没有对应的markdown文章
分类列表页面               // [taxonomyTerm]    <- https://example.com/categories/  **
某个分类下的所有文章的列表  // [taxonomy]        <- https://example.com/categories/one-category  **
标签列表页面               // [taxonomyTerm]    <- https://example.com/tags/  **
某个标签下的所有文章的列表  // [taxonomy]        <- https://example.com/tags/one-tag  **

functions

delimit函数, 相当于explode函数

// Front matter
// Used anywhere in a template
Tags: {{ delimit .Params.tags ", " }}

// Outputs Tags: tag1, tag2, tag3

// Example with the optional "last" parameter
Tags: {{ delimit .Params.tags ", " " and " }}

// Outputs Tags: tag1, tag2 and tag3

dict函数

字典可以传递给模板

{{$important := .Site.Params.SomethingImportant }}
{{range .Site.Params.Bar}}
    {{partial "foo" (dict "content" . "important" $important)}}
{{end}}

“foo.html”

Important {{.important}}
{{.content}}

echoParam 函数,打印参数

{{ echoParam .Params "project_url" }}

eq 函数, 如果相等则返回true

{{ if eq .Section "blog" }}current{{ end }}

first函数 , 只遍历前10个元素

{{ range first 10 .Data.Pages }}
    {{ .Render "summary" }}
{{ end }}

last函数,只遍历最后10个元素

{{ range last 10 .Data.Pages }}
    {{ .Render "summary" }}
{{ end }}

after函数

{{ range after 10 .Data.Pages }}
    {{ .Render "title" }}
{{ end }}

getenv函数

{{ getenv "HOME" }}

in函数

{{ if in .Params.tags "Git" }}Follow me on GitHub!{{ end }}

or

{{ if in "this string contains a substring" "substring" }}Substring found!{{ end }}

intersect函数, 求两个数组的交集

<ul>
{{ $page_link := .Permalink }}
{{ $tags := .Params.tags }}
{{ range .Site.Pages }}
    {{ $page := . }}
    {{ $has_common_tags := intersect $tags .Params.tags | len | lt 0 }}
    {{ if and $has_common_tags (ne $page_link $page.Permalink) }}
        <li><a href="{{ $page.Permalink }}">{{ $page.Title }}</a></li>
    {{ end }}
{{ end }}
</ul>

isset函数, 值是否被设置。已设置返回true

{{ if isset .Params "project_url" }} {{ index .Params "project_url" }}{{ end }}

seq 整数序列

sort函数。排列数组,切片,map。 返回sorted slice

// Front matter
// Site config
// Use default sort options - sort by key / ascending
Tags: {{ range sort .Params.tags }}{{ . }} {{ end }}

// Outputs Tags: tag1 tag2 tag3

// Sort by value / descending
Tags: {{ range sort .Params.tags "value" "desc" }}{{ . }} {{ end }}

// Outputs Tags: tag3 tag2 tag1

// Use default sort options - sort by value / descending
Authors: {{ range sort .Site.Params.authors }}{{ .firstName }} {{ end }}

// Outputs Authors: Derek Joe Tanner

// Use default sort options - sort by value / descending
Authors: {{ range sort .Site.Params.authors "lastName" "desc" }}{{ .lastName }} {{ end }}

// Outputs Authors: Perkins Linsley Bergevin

where

// Front matter on some pages
{{ range where .Site.Pages "Params.series" "golang" }}
   {{ .Content }}
{{ end }}

chomp

删除字符串末尾的\n

highlight

lower

转小写

markdownify

经过markdown处理器过滤。go模板不会过滤。

{{ .Title | markdownify }}

pluralize 变成复数名词

{{ "cat" | pluralize }} → “cats”

replace

{{ replace "Batman and Robin" "Robin" "Catwoman" }} → “Batman and Catwoman”

safeHTML

copyright = "© 2015 Jane Doe.  <a href=\"http://creativecommons.org/licenses/by/4.0/\">Some rights reserved</a>."
{{ .Site.Copyright | safeHTML }} would then output:
© 2015 Jane Doe. Some rights reserved.

safeCSS

Example: Given style = "color: red;" defined in the front matter of your .md file:

<p style="{{ .Params.style | safeCSS }}">…</p> ⇒ <p style="color: red;">…</p> (Good!)
<p style="{{ .Params.style }}">…</p> ⇒ <p style="ZgotmplZ">…</p> (Bad!)

safeJS

Example: Given hash = "619c16f" defined in the front matter of your .md file:

<script>var form_{{ .Params.hash | safeJS }};…</script> ⇒ <script>var form_619c16f;…</script> (Good!)
<script>var form_{{ .Params.hash }};…</script> ⇒ <script>var form_"619c16f";…</script> (Bad!)

singularize 转单数

{{ "cats" | singularize }} → “cat”

slicestr

{{slicestr "BatMan" 3}} → “Man”
{{slicestr "BatMan" 0 3}} → “Bat”

substr

{{substr "BatMan" 0 -3}} → “Bat”
{{substr "BatMan" 3 3}} → “Man”

title

{{title "BatMan"}} → “Batman”

trim

{{ trim "

## upper 

```go
{{upper "BatMan"}} → “BATMAN”

URLs

{{ "mystyle.css" | absURL }} → “http://mysite.com/hugo/mystyle.css"
{{ "mystyle.css" | relURL }} → “/hugo/mystyle.css”
{{ "http://gohugo.io/" | relURL }} → “http://gohugo.io/"
{{ "http://gohugo.io/" | absURL }} → “http://gohugo.io/"

Page 变量

Tile 文章的标题

Content 文章内容

Summary 文章内容摘要

Truncated 如果是true,会显示 阅读更多链接

Description 文章描述

Keywords 文章元数据 keywords

Date 关联的日期

PublishDate 文章发布时间

Type 文章类型

Section 文章的归属

Permalink 文章的固定链接

RelPermalink 文章相对永久链接

LinkTitle

RSSLink

TableOfContents 文章目录, markdown 目录必须是##(二级标题) 不能是#

Prev 上一篇文章

Next 下一篇文章

PrevInSection

NextInSection

FuzzyWordCount 文章大致字数

WordCount文章字数

ReadingTime 阅读需要的时间

Weight 权重,用于文章排序

** RawContent** 没有元数据头的markdown内容 Useful with remarkjs.com

Draft 是否标记为草稿,true是

IsNode 对于页面总是false

IsPage 对于页面总是true

Site 网站相关的数据,是个对象

Hugo huog相关的数据,也是对象

页面参数

markdown文件头部数据,可以用 .Params.tags的方式访问

访问只能用小写方式

<a href='{{ .Params.baidu }}'>百度</a>
或者
<a href='{{ $.Params.baidu }}'>百度</a>

$.Param 方法

$.Param("image") 可以安全的在模板中使用

<a href='{{ $.Param "baidu" }}'>百度</a>

结点变量(node Varibles)

Title 文章标题

Date 文章发布时间

Permalink 文章永久链接

URL 相对于Node的链接

Ref(ref) 返回ref的永久链接

RelRef(ref) 返回ref的相对链接

Data 传递给结点的数据

isHome 如果Node是主页,则是true

isNode 如果时候node,则是true

isPage 如果是node,则是false

Site 网站对象

Hugo hugo对象

Taxonomy term 变量

Data.Singular 单数形式的分类名

Data.Plural 复数形式的分类名

Data.Pages taxonomy 这个分类的pages列表

Data.Terms 分类本身

Data.Terms.Alphabetical 按字母顺序排序

Data.Terms.ByCount 按欢迎度排序

.Data.Terms.Alphabetical.Reverse 倒序

.Data.Terms.ByCount.Reverse 倒序

Site 变量

Site.BaseURL 配置文件中的BaseUrl

Site.RSSLink rss site的URL

Site.Taxonomies 整个站点的分类方法, 取代.Site.Indexes 从v0.11开始

SIte.Pages 返回全部文章,按日期倒序 取代旧方法 .Site.Recent 从 v0.13

Site.Params 站点配置文件中的params 部分的值

baseurl = "http://yoursite.example.com/"

[params]
  description = "Tesla's Awesome Hugo Site"
  author = "Nikola Tesla"

.Site.Sections 网站顶级目录

Site.Files 全部source 文件

Site.Menus 网站菜单

Site.TItle 站点标题字符串

Site.Author 作者

Site.LanguageCode 定义的网站语言

Site.DisqusShortname 定义的短代码名称

Site.GoogleAnalystics 谷歌跟踪代码

Site.Copyright

Site.LastChange

Site.BuildDrafts 是都构建草稿, 默认false

Site.Data 用户Data

​ data目录下,可以是json,yml,yaml,toml格式,类似通过Api接口拿到的数据

Hugo 变量

.Hugo.Generator Meta tag for the version of Hugo that generated the site. Highly recommended to be included by default in all theme headers so we can start to track Hugo usage and popularity. e.g. <meta name="generator" content="Hugo 0.13" />
.Hugo.Version The current version of the Hugo binary you are using e.g. 0.13-DEV
.Hugo.CommitHash The git commit hash of the current Hugo binary e.g. 0e8bed9ccffba0df554728b46c5bbf6d78ae5247
.Hugo.BuildDate The compile date of the current Hugo binary formatted with RFC 3339 e.g. 2002-10-02T10:00:00-05:00

数据驱动, 获取json或者csv

{{ $data = getJSON  "http://127.0.0.1/1.json" }}
或者
{{ $data = getJSON "http://127.0.0.1/" "1.json"}}

或者本地文件
{{ $data = getJSON "/data/test.json" }}


CSV 文件
{{ $data = getCSV "," "http://127.0.0.1/1.csv"}} 第二个参数是分隔符

json 渲染

  
  {{ $dataJ := getJSON  "/data/test.json"}}
  
  <p>{{.Permalink}}</p>
  <div>
    <p class="text-info"> 这里是 data json数据: </p>
    {{/*  {{ range $.Site.Data.test.list }}  */}}
    {{ range first 5 $dataJ.list }}
      <span class="text-danger">
        &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp {{ . }} <br>
      </span>   
    {{ end}}
  </div>

Csv 渲染

<table>
  <thead>
    <tr>
    <th>Name</th>
    <th>Position</th>
    <th>Salary</th>
    </tr>
  </thead>
  <tbody>
  {{ $url := "http://a-big-corp.com/finance/employee-salaries.csv" }}
  {{ $sep := "," }}
  {{ range $i, $r := getCSV $sep $url }}
    <tr>
      <td>{{ index $r 0 }}</td>
      <td>{{ index $r 1 }}</td>
      <td>{{ index $r 2 }}</td>
    </tr>
  {{ end }}
  </tbody>
</table>

标签:end,框架,hugo,Site,range,html,Params,模板
From: https://www.cnblogs.com/hystill/p/16815564.html

相关文章

  • 定时器、外部中断0,以及查询和中断的模板
    这里拿一个0-60秒表做案例://sbit定义四个数码管unsignedcharcount,miao;voidmain(){  TMOD=0X01;  //设置T0为工作方式1  TH0=0XEE;    TL0=0X00......
  • 模板字符串
    模板字符串在ES5当中,当需要把多个字符串和多个变量拼接至一起时,写法相当的复杂varname="狗蛋",age=12,gender="男生"varstr="大家好,我是"+name+",今年"+age+"岁了,......
  • 不妨试试更快更小更灵活Java开发框架Solon
    @目录概述定义性能架构实战SolonWeb示例SolonMybatis-Plus示例SolonWebSocket示例SolonRemotingRPC示例SolonCloudNacos示例概述定义Solon官网地址https://so......
  • 手写基于Java RMI的RPC框架
    留给读者其中最大的区别就是ZooKeeper注册中心,注册中心可以有读写监听器,这是一个优势,可以用来实现订阅通知,也能做数据的同步,甚至可以做基于读写分离的RPC框架,而且它是基......
  • 树状数组两种修改+求和 | 模板
    \(O(mlogn)\),单次查询为\(O(logn)\)实际最坏情况下优于线段树,因为跑不满...1.单点修改+区间求和区间求和变为前缀和相减。#include<iostream>#include<cstdio>const......
  • 微服务组件--限流框架Spring Cloud Hystrix分析
    Hystrix的介绍【1】Hystrix是springCloud的组件之一,Hystrix可以让我们在分布式系统中对服务间的调用进行控制加入一些调用延迟或者依赖故障的容错机制。【2】Hystrix通......
  • SpringBoot2.0上启动RPC框架RNF2.0已发布
    使用效果:用户访问客户端:GEThttp://localhost:8081/user/hello?name="张三来访"浏览器访问客户端:服务端接收情况:服务端负载注册服务:上面的实现就好比客户端只......
  • 基于链式前向星的堆优化dijsktra | 模板
    关于SPFA,ta死了基于链式前向星的堆优化\(dijsktra\):复杂度\(O(mlogn)\),要求非负权。#include<iostream>#include<cstdio>#include<cstring>#include<queue>#inc......
  • robotframework自动化测试框架实战教程:创建及使用监听器(listener)接口
    RobotFramework提供了一个监听器(listener)接口可以用来接收测试执行过程中的通知. 监听器通过在命令行中设置选项 --listener 来启用,和导入测试库类似,你也可以指定......
  • 前端笔记-内联框架-20221021
    HTMLIframe1.定义:用于在网页内显示网页。2.语法<iframesrc="URL"></iframe>3.内联框架属性height:规定高度width:规定宽度frameborder:属性规定是否显示ifra......