Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
G
golang
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Commits
Issue Boards
Open sidebar
go
golang
Commits
26c2443d
Commit
26c2443d
authored
Feb 28, 2012
by
Rob Pike
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
text/template: add example showing use of custom function
R=golang-dev, adg CC=golang-dev
https://golang.org/cl/5694100
parent
180541b2
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
54 additions
and
0 deletions
+54
-0
examplefunc_test.go
src/pkg/text/template/examplefunc_test.go
+54
-0
No files found.
src/pkg/text/template/examplefunc_test.go
0 → 100644
View file @
26c2443d
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package
template_test
import
(
"log"
"os"
"strings"
"text/template"
)
// This example demonstrates a custom function to process template text.
// It installs the strings.Title function and uses it to
// Make Title Text Look Good In Our Template's Output.
func
ExampleTemplate_func
()
{
// First we create a FuncMap with which to register the function.
funcMap
:=
template
.
FuncMap
{
// The name "title" is what the function will be called in the template text.
"title"
:
strings
.
Title
,
}
// A simple template definition to test our function.
// We print the input text several ways:
// - the original
// - title-cased
// - title-cased and then printed with %q
// - printed with %q and then title-cased.
const
templateText
=
`
Input: {{printf "%q" .}}
Output 0: {{title .}}
Output 1: {{title . | printf "%q"}}
Output 2: {{printf "%q" . | title}}
`
// Create a template, add the function map, and parse the text.
tmpl
,
err
:=
template
.
New
(
"titleTest"
)
.
Funcs
(
funcMap
)
.
Parse
(
templateText
)
if
err
!=
nil
{
log
.
Fatalf
(
"parsing: %s"
,
err
)
}
// Run the template to verify the output.
err
=
tmpl
.
Execute
(
os
.
Stdout
,
"the go programming language"
)
if
err
!=
nil
{
log
.
Fatalf
(
"execution: %s"
,
err
)
}
// Output:
// Input: "the go programming language"
// Output 0: The Go Programming Language
// Output 1: "The Go Programming Language"
// Output 2: "The Go Programming Language"
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment