Template inheritance is a powerful feature of Jinja2 . Here we show how to mimic
the template extends of Jinja2 in Go html/template .
Go html/template versue Python Jinja2 -
Template Inheritance (Extends )
Go html/template
Python Jinja2
"base" template:
{{ define "base" }}
<! doctype html >
< html >
< head >
< meta charset = "utf-8" >
< title >{{ template "title" .}}< / title >
< / head >
< body >
{{ template "content" .}}
< / body >
< / html >
{{ end }}
"base" template:
< ! doctype html >
< html >
< head >
< meta charset = "utf-8" >
< title > { % block title % }{ % endblock % } </ title >
</ head >
< body >
{ % block content % }{ % endblock % }
</ body >
</ html >
index.html:
{{ template "base" .}}
{{ define "title" }} my title {{ end }}
{{ define "content" }}
< div > hello {{.}}< / div >
{{ end }}
index.html:
{ % extends "base.html" % }
{ % block title % } my title { % endblock % }
{ % block content % }
< div > hello {{ name }} </ div >
{ % endblock % }
Complete Go html/template source code:
base-go.html |
repository |
view raw
1
2
3
4
5
6
7
8
9
10
11
12 {{ define "base" }}
<!doctype html>
< html >
< head >
< meta charset = "utf-8" >
< title > {{ template "title" . }} </ title >
</ head >
< body >
{{ template "content" . }}
</ body >
</ html >
{{ end }}
index-go.html |
repository |
view raw
{{ template "base" . }}
{{ define "title" }} my title{{ end }}
{{ define "content" }}
< div > hello {{ . }} </ div >
{{ end }}
extends.go |
repository |
view raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package main
import (
"html/template"
"os"
)
func main () {
// cannot put base-go.html before index-go.html
// the following will give empty output
//t, _ := template.ParseFiles("base-go.html", "index-go.html")
t , _ := template . ParseFiles ( "index-go.html" , "base-go.html" )
name := "world"
t . Execute ( os . Stdout , name )
}
Complete Python Jinja2 source code:
base.html |
repository |
view raw
<!doctype html>
< html >
< head >
< meta charset = "utf-8" >
< title > {% block title %}{% endblock %} </ title >
</ head >
< body >
{% block content %}{% endblock %}
</ body >
</ html >
index.html |
repository |
view raw
{% extends "base.html" %}
{% block title %} my title{% endblock %}
{% block content %}
< div > hello {{ name }} </ div >
{% endblock %}
extends.py |
repository |
view raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 #!/usr/bin/env python
# -*- coding:utf-8 -*-
import jinja2
import os
JINJA_ENVIRONMENT = jinja2 . Environment (
loader = jinja2 . FileSystemLoader ( os . path . dirname ( __file__ )),
extensions = [ 'jinja2.ext.autoescape' ],
autoescape = True )
if __name__ == '__main__' :
template_values = {
'name' : 'world' ,
}
template = JINJA_ENVIRONMENT . get_template ( 'index.html' )
print ( template . render ( template_values ))
Tested on: Ubuntu Linux 14.10 , Go 1.4 , Python 2.7.8 , Jinja2 2.7.3
Golang html/template versus Python Jinja2 series:
References: