go的html模板替换

来源:互联网 发布:unity3d 5.3.2f1 破解 编辑:程序博客网 时间:2024/06/05 03:45
  1、模版注入函数

     t.Funcs()


  2、字符串作为模版

     Template.Must


  3、模版的Map或者Struct替换
      t := template.New(“index.html”)  -----创建模板
      t.ParseFiles(“index.html”)   ----找到其中需要替换的模板变量

      t.Execute(os.StdOut,yourMapObj_or_structOjb)   -------执行模板的替换


  4、模版语言
       {{.UserName}}   用Struct来替换
       {{.username}}    用Map来替换
     定义模板
        {{define "main"}}
           {{range .Name}}
                 {{.}}
           {{end}}

        {{end}

  5、模板继承的使用方式

       type UserList struct {
                Id   []int
                Name []string
       }

      var templates = template.Must(template.ParseFiles("main.html"))  //可能会触发解析多个文件,包括基础模板

      func rootHandler(w http.ResponseWriter, r *http.Request) 
      {
             users := UserList{
                Id:   []int{0, 1, 2, 3, 4, 5, 6, 7},
                Name: []string{"user0", "user1", "user2", "user3", "user4"},
             }
             templates.ExecuteTemplate(w, "main", &users)

      }

     6、模板语言的样例

       template/base.html
                 <html>
                      <meta http-equiv="Content-type" content="text/html; charset=utf-8">
                       <title>{% block title %}{% endblock %}</title>
                       <head></head>
                       <body>
                          <h3>{% block headTitle %} {% endblock %}</h3>
                                {% block content %}  {% endblock %}
                                {% block footer %}
                                     <h3>嘿,这是继承了模版</h3>
                                {% endblock%}
                       </body>
                </html>

       template/user_info.html
             {% extends "base.html" %}
             {% block title %}用户信息{% endblock %}
             <h3>{% block headTitle %}用户信息:{% endblock %}</h3>
                     {% block content %}
                   <p>姓名:{{name}}</p>
                   <p>年龄:{{age}}</p>
                      {% endblock %}


      7、替换的原则
            分为模版变量(block content)和模版标签(block title)
                 {% block content %} {% endblock %}
                block就是关键字,后面才是变量名,block表示代码块的意思
                派生的模版替覆盖base模版中的模版标签
                派生的模版替换base模版中的模版变量         

原创粉丝点击