CINXE.COM
template package - text/template - Go Packages
<!DOCTYPE html> <html lang="en" data-layout="responsive" data-local=""> <head> <script> window.addEventListener('error', window.__err=function f(e){f.p=f.p||[];f.p.push(e)}); </script> <script> (function() { const theme = document.cookie.match(/prefers-color-scheme=(light|dark|auto)/)?.[1] if (theme) { document.querySelector('html').setAttribute('data-theme', theme); } }()) </script> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="Description" content="Package template implements data-driven templates for generating textual output."> <meta class="js-gtmID" data-gtmid="GTM-W8MVQXG"> <link rel="shortcut icon" href="/static/shared/icon/favicon.ico"> <link rel="canonical" href="https://pkg.go.dev/text/template"> <link href="/static/frontend/frontend.min.css?version=prod-frontend-00095-8lw" rel="stylesheet"> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="Go Packages"> <title>template package - text/template - Go Packages</title> <link href="/static/frontend/unit/unit.min.css?version=prod-frontend-00095-8lw" rel="stylesheet"> <link href="/static/frontend/unit/main/main.min.css?version=prod-frontend-00095-8lw" rel="stylesheet"> </head> <body> <script> function loadScript(src, mod = true) { let s = document.createElement('script'); s.src = src; if (mod) { s.type = 'module'; s.async = true; s.defer = true } document.head.appendChild(s); } loadScript("/third_party/dialog-polyfill/dialog-polyfill.js", false) loadScript("/static/frontend/frontend.js"); </script> <header class="go-Header go-Header--full js-siteHeader"> <div class="go-Header-inner go-Header-inner--dark"> <nav class="go-Header-nav"> <a href="https://go.dev/" class="js-headerLogo" data-gtmc="nav link" data-test-id="go-header-logo-link" role="heading" aria-level="1"> <img class="go-Header-logo" src="/static/shared/logo/go-white.svg" alt="Go"> </a> <div class="skip-navigation-wrapper"> <a class="skip-to-content-link" aria-label="Skip to main content" href="#main-content"> Skip to Main Content </a> </div> <div class="go-Header-rightContent"> <div class="go-SearchForm js-searchForm"> <form class="go-InputGroup go-ShortcutKey go-SearchForm-form" action="/search" data-shortcut="/" data-shortcut-alt="search" data-gtmc="search form" aria-label="Search for a package" role="search" > <input name="q" class="go-Input js-searchFocus" aria-label="Search for a package" type="search" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" placeholder="Search packages or symbols" value="" /> <input name="m" value="" hidden> <button class="go-Button go-Button--inverted" aria-label="Submit search"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/search_gm_grey_24dp.svg" alt="" /> </button> </form> <button class="go-SearchForm-expandSearch js-expandSearch" data-gtmc="nav button" aria-label="Open search" data-test-id="expand-search"> <img class="go-Icon go-Icon--inverted" height="24" width="24" src="/static/shared/icon/search_gm_grey_24dp.svg" alt=""> </button> </div> <ul class="go-Header-menu"> <li class="go-Header-menuItem"> <a class="js-desktop-menu-hover" href="#" data-gtmc="nav link"> Why Go <img class="go-Icon" height="24" width="24" src="/static/shared/icon/arrow_drop_down_gm_grey_24dp.svg" alt="submenu dropdown icon"> </a> <ul class="go-Header-submenu go-Header-submenu--why js-desktop-submenu-hover" aria-label="submenu"> <li class="go-Header-submenuItem"> <div> <a href="https://go.dev/solutions#case-studies"> <span>Case Studies</span> </a> </div> <p>Common problems companies solve with Go</p> </li> <li class="go-Header-submenuItem"> <div> <a href="https://go.dev/solutions#use-cases"> <span>Use Cases</span> </a> </div> <p>Stories about how and why companies use Go</p> </li> <li class="go-Header-submenuItem"> <div> <a href="https://go.dev/security/policy/"> <span>Security Policy</span> </a> </div> <p>How Go can help keep you secure by default</p> </li> </ul> </li> <li class="go-Header-menuItem"> <a href="https://go.dev/learn/" data-gtmc="nav link">Learn</a> </li> <li class="go-Header-menuItem"> <a class="js-desktop-menu-hover" href="#" data-gtmc="nav link"> Docs <img class="go-Icon" height="24" width="24" src="/static/shared/icon/arrow_drop_down_gm_grey_24dp.svg" alt="submenu dropdown icon"> </a> <ul class="go-Header-submenu go-Header-submenu--docs js-desktop-submenu-hover" aria-label="submenu"> <li class="go-Header-submenuItem"> <div> <a href="https://go.dev/doc/effective_go"> <span>Effective Go</span> </a> </div> <p>Tips for writing clear, performant, and idiomatic Go code</p> </li> <li class="go-Header-submenuItem"> <div> <a href="https://go.dev/doc/"> <span>Go User Manual</span> </a> </div> <p>A complete introduction to building software with Go</p> </li> <li class="go-Header-submenuItem"> <div> <a href="https://pkg.go.dev/std"> <span>Standard library</span> </a> </div> <p>Reference documentation for Go's standard library</p> </li> <li class="go-Header-submenuItem"> <div> <a href="https://go.dev/doc/devel/release"> <span>Release Notes</span> </a> </div> <p>Learn what's new in each Go release</p> </li> </ul> </li> <li class="go-Header-menuItem go-Header-menuItem--active"> <a href="/" data-gtmc="nav link">Packages</a> </li> <li class="go-Header-menuItem"> <a class="js-desktop-menu-hover" href="#" data-gtmc="nav link"> Community <img class="go-Icon" height="24" width="24" src="/static/shared/icon/arrow_drop_down_gm_grey_24dp.svg" alt="submenu dropdown icon"> </a> <ul class="go-Header-submenu go-Header-submenu--community js-desktop-submenu-hover" aria-label="submenu"> <li class="go-Header-submenuItem"> <div> <a href="https://go.dev/talks/"> <span>Recorded Talks</span> </a> </div> <p>Videos from prior events</p> </li> <li class="go-Header-submenuItem"> <div> <a href="https://www.meetup.com/pro/go"> <span>Meetups</span> <i class="material-icons"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/launch_gm_grey_24dp.svg" alt=""> </i> </a> </div> <p>Meet other local Go developers</p> </li> <li class="go-Header-submenuItem"> <div> <a href="https://github.com/golang/go/wiki/Conferences"> <span>Conferences</span> <i class="material-icons"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/launch_gm_grey_24dp.svg" alt=""> </i> </a> </div> <p>Learn and network with Go developers from around the world</p> </li> <li class="go-Header-submenuItem"> <div> <a href="https://go.dev/blog"> <span>Go blog</span> </a> </div> <p>The Go project's official blog.</p> </li> <li class="go-Header-submenuItem"> <div> <a href="https://go.dev/help"> <span>Go project</span> </a> </div> <p>Get help and stay informed from Go</p> </li> <li class="go-Header-submenuItem"> <div> Get connected </div> <p></p> <div class="go-Header-socialIcons"> <a class="go-Header-socialIcon" aria-label="Get connected with google-groups (Opens in new window)" title="Get connected with google-groups (Opens in new window)" href="https://groups.google.com/g/golang-nuts"> <img src="/static/shared/logo/social/google-groups.svg" /> </a> <a class="go-Header-socialIcon" aria-label="Get connected with github (Opens in new window)" title="Get connected with github (Opens in new window)" href="https://github.com/golang"> <img src="/static/shared/logo/social/github.svg" /> </a> <a class="go-Header-socialIcon" aria-label="Get connected with twitter (Opens in new window)" title="Get connected with twitter (Opens in new window)" href="https://twitter.com/golang"> <img src="/static/shared/logo/social/twitter.svg" /> </a> <a class="go-Header-socialIcon" aria-label="Get connected with reddit (Opens in new window)" title="Get connected with reddit (Opens in new window)" href="https://www.reddit.com/r/golang/"> <img src="/static/shared/logo/social/reddit.svg" /> </a> <a class="go-Header-socialIcon" aria-label="Get connected with slack (Opens in new window)" title="Get connected with slack (Opens in new window)" href="https://invite.slack.golangbridge.org/"> <img src="/static/shared/logo/social/slack.svg" /> </a> <a class="go-Header-socialIcon" aria-label="Get connected with stack-overflow (Opens in new window)" title="" href="https://stackoverflow.com/collectives/go"> <img src="/static/shared/logo/social/stack-overflow.svg" /> </a> </div> </li> </ul> </li> </ul> <button class="go-Header-navOpen js-headerMenuButton go-Header-navOpen--white" data-gtmc="nav button" aria-label="Open navigation"> </button> </div> </nav> </div> </header> <aside class="go-NavigationDrawer js-header"> <nav class="go-NavigationDrawer-nav"> <div class="go-NavigationDrawer-header"> <a href="https://go.dev/"> <img class="go-NavigationDrawer-logo" src="/static/shared/logo/go-blue.svg" alt="Go."> </a> </div> <ul class="go-NavigationDrawer-list"> <li class="go-NavigationDrawer-listItem js-mobile-subnav-trigger go-NavigationDrawer-hasSubnav"> <a href="#"> <span>Why Go</span> <i class="material-icons"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/navigate_next_gm_grey_24dp.svg" alt=""> </i> </a> <div class="go-NavigationDrawer go-NavigationDrawer-submenuItem"> <div class="go-NavigationDrawer-nav"> <div class="go-NavigationDrawer-header"> <a href="#"> <i class="material-icons"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/navigate_before_gm_grey_24dp.svg" alt=""> </i> Why Go </a> </div> <ul class="go-NavigationDrawer-list"> <li class="go-NavigationDrawer-listItem"> <a href="https://go.dev/solutions#case-studies"> Case Studies </a> </li> <li class="go-NavigationDrawer-listItem"> <a href="https://go.dev/solutions#use-cases"> Use Cases </a> </li> <li class="go-NavigationDrawer-listItem"> <a href="https://go.dev/security/policy/"> Security Policy </a> </li> </ul> </div> </div> </li> <li class="go-NavigationDrawer-listItem"> <a href="https://go.dev/learn/">Learn</a> </li> <li class="go-NavigationDrawer-listItem js-mobile-subnav-trigger go-NavigationDrawer-hasSubnav"> <a href="#"> <span>Docs</span> <i class="material-icons"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/navigate_next_gm_grey_24dp.svg" alt=""> </i> </a> <div class="go-NavigationDrawer go-NavigationDrawer-submenuItem"> <div class="go-NavigationDrawer-nav"> <div class="go-NavigationDrawer-header"> <a href="#"><i class="material-icons"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/navigate_before_gm_grey_24dp.svg" alt=""> </i> Docs </a> </div> <ul class="go-NavigationDrawer-list"> <li class="go-NavigationDrawer-listItem"> <a href="https://go.dev/doc/effective_go"> Effective Go </a> </li> <li class="go-NavigationDrawer-listItem"> <a href="https://go.dev/doc/"> Go User Manual </a> </li> <li class="go-NavigationDrawer-listItem"> <a href="https://pkg.go.dev/std"> Standard library </a> </li> <li class="go-NavigationDrawer-listItem"> <a href="https://go.dev/doc/devel/release"> Release Notes </a> </li> </ul> </div> </div> </li> <li class="go-NavigationDrawer-listItem go-NavigationDrawer-listItem--active"> <a href="/">Packages</a> </li> <li class="go-NavigationDrawer-listItem js-mobile-subnav-trigger go-NavigationDrawer-hasSubnav"> <a href="#"> <span>Community</span> <i class="material-icons"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/navigate_next_gm_grey_24dp.svg" alt=""> </i> </a> <div class="go-NavigationDrawer go-NavigationDrawer-submenuItem"> <div class="go-NavigationDrawer-nav"> <div class="go-NavigationDrawer-header"> <a href="#"> <i class="material-icons"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/navigate_before_gm_grey_24dp.svg" alt=""> </i> Community </a> </div> <ul class="go-NavigationDrawer-list"> <li class="go-NavigationDrawer-listItem"> <a href="https://go.dev/talks/"> Recorded Talks </a> </li> <li class="go-NavigationDrawer-listItem"> <a href="https://www.meetup.com/pro/go"> Meetups <i class="material-icons"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/launch_gm_grey_24dp.svg" alt=""> </i> </a> </li> <li class="go-NavigationDrawer-listItem"> <a href="https://github.com/golang/go/wiki/Conferences"> Conferences <i class="material-icons"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/launch_gm_grey_24dp.svg" alt=""> </i> </a> </li> <li class="go-NavigationDrawer-listItem"> <a href="https://go.dev/blog"> Go blog </a> </li> <li class="go-NavigationDrawer-listItem"> <a href="https://go.dev/help"> Go project </a> </li> <li class="go-NavigationDrawer-listItem"> <div>Get connected</div> <div class="go-Header-socialIcons"> <a class="go-Header-socialIcon" href="https://groups.google.com/g/golang-nuts"><img src="/static/shared/logo/social/google-groups.svg" /></a> <a class="go-Header-socialIcon" href="https://github.com/golang"><img src="/static/shared/logo/social/github.svg" /></a> <a class="go-Header-socialIcon" href="https://twitter.com/golang"><img src="/static/shared/logo/social/twitter.svg" /></a> <a class="go-Header-socialIcon" href="https://www.reddit.com/r/golang/"><img src="/static/shared/logo/social/reddit.svg" /></a> <a class="go-Header-socialIcon" href="https://invite.slack.golangbridge.org/"><img src="/static/shared/logo/social/slack.svg" /></a> <a class="go-Header-socialIcon" href="https://stackoverflow.com/collectives/go"><img src="/static/shared/logo/social/stack-overflow.svg" /></a> </div> </li> </ul> </div> </div> </li> </ul> </nav> </aside> <div class="go-NavigationDrawer-scrim js-scrim" role="presentation"></div> <main class="go-Main" id="main-content"> <div class="go-Main-banner" role="alert"></div> <header class="go-Main-header js-mainHeader"> <nav class="go-Main-headerBreadcrumb go-Breadcrumb" aria-label="Breadcrumb" data-test-id="UnitHeader-breadcrumb"> <ol> <li data-test-id="UnitHeader-breadcrumbItem"> <a href="/" data-gtmc="breadcrumb link">Discover Packages</a> </li> <li data-test-id="UnitHeader-breadcrumbItem"> <a href="/std" data-gtmc="breadcrumb link">Standard library</a> </li> <li data-test-id="UnitHeader-breadcrumbItem"> <a href="/text" data-gtmc="breadcrumb link">text</a> </li> <li> <a href="/text/template@go1.24.0" data-gtmc="breadcrumb link" aria-current="location" data-test-id="UnitHeader-breadcrumbCurrent"> template </a> <button class="go-Button go-Button--inline go-Clipboard js-clipboard" title="Copy path to clipboard. text/template" aria-label="Copy Path to Clipboard" data-to-copy="text/template" data-gtmc="breadcrumbs button" > <img class="go-Icon go-Icon--accented" height="24" width="24" src="/static/shared/icon/content_copy_gm_grey_24dp.svg" alt="" > </button> </li> </ol> </nav> <div class="go-Main-headerContent"> <div class="go-Main-headerTitle js-stickyHeader"> <a class="go-Main-headerLogo" href="https://go.dev/" aria-hidden="true" tabindex="-1" data-gtmc="header link" aria-label="Link to Go Homepage"> <img height="78" width="207" src="/static/shared/logo/go-blue.svg" alt="Go"> </a> <h1 class="UnitHeader-titleHeading" data-test-id="UnitHeader-title">template</h1> <span class="go-Chip go-Chip--inverted">package</span> <span class="go-Chip go-Chip--inverted">standard library</span> <button class="go-Button go-Button--inline go-Clipboard js-clipboard" title="Copy path to clipboard. text/template" aria-label="Copy Path to Clipboard" data-to-copy="text/template" data-gtmc="title button" tabindex="-1" > <img class="go-Icon go-Icon--accented" height="24" width="24" src="/static/shared/icon/content_copy_gm_grey_24dp.svg" alt="" /> </button> </div> <div class="go-Main-headerDetails"> <span class="go-Main-headerDetailItem" data-test-id="UnitHeader-version"> <a href="?tab=versions" aria-label="Version: go1.24.0" data-gtmc="header link" aria-describedby="version-description"> <span class="go-textSubtle" aria-hidden="true">Version: </span> go1.24.0 </a> <div class="screen-reader-only" id="version-description" hidden> Opens a new window with list of versions in this module. </div> <span class="DetailsHeader-badge--latest" data-test-id="UnitHeader-minorVersionBanner"> <span class="go-Chip DetailsHeader-span--latest">Latest</span> <span class="go-Chip DetailsHeader-span--notAtLatest"> Latest <details class="go-Tooltip js-tooltip" data-gtmc="tooltip"> <summary> <img class="go-Icon go-Icon--inverted" height="24" width="24" src="/static/shared/icon/alert_gm_grey_24dp.svg" alt="Warning"> </summary> <p>This package is not in the latest version of its module.</p> </details> </span> <a href="/text/template" aria-label="Go to Latest Version" data-gtmc="header link"> <span class="go-Chip go-Chip--alert DetailsHeader-span--goToLatest">Go to latest</span> </a> </span> </span> <span class="go-Main-headerDetailItem" data-test-id="UnitHeader-commitTime"> Published: Feb 11, 2025 </span> <span class="go-Main-headerDetailItem" data-test-id="UnitHeader-licenses"> License: <a href="/text/template?tab=licenses" data-test-id="UnitHeader-license" data-gtmc="header link" aria-describedby="license-description">BSD-3-Clause</a> </span> <div class="screen-reader-only" id="license-description" hidden> Opens a new window with license information. </div> <span class="go-Main-headerDetailItem" data-test-id="UnitHeader-imports"> <a href="/text/template?tab=imports" aria-label="Imports: 17" data-gtmc="header link" aria-describedby="imports-description"> <span class="go-textSubtle">Imports: </span>17 </a> </span> <div class="screen-reader-only" id="imports-description" hidden> Opens a new window with list of imports. </div> <span class="go-Main-headerDetailItem" data-test-id="UnitHeader-importedby"> <a href="/text/template?tab=importedby" aria-label="Imported By: 101,406" data-gtmc="header link" aria-describedby="importedby-description"> <span class="go-textSubtle">Imported by: </span>101,406 </a> </span> <div class="screen-reader-only" id="importedby-description" hidden> Opens a new window with list of known importers. </div> </div> <div class="UnitHeader-overflowContainer"> <svg class="UnitHeader-overflowImage" xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"> <path d="M0 0h24v24H0z" fill="none"/> <path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/> </svg> <select class="UnitHeader-overflowSelect js-selectNav" tabindex="-1"> <option value="/">Main</option> <option value="/text/template?tab=versions"> Versions </option> <option value="/text/template?tab=licenses"> Licenses </option> <option value="/text/template?tab=imports"> Imports </option> <option value="/text/template?tab=importedby"> Imported By </option> </select> </div> </div> </header> <aside class="go-Main-aside js-mainAside"> <div class="UnitMeta"> <h2 class="go-textLabel">Details</h2> <ul class="UnitMeta-details"> <li> <details class="go-Tooltip js-tooltip" data-gtmc="tooltip"> <summary class="go-textSubtle"> <img class="go-Icon go-Icon--accented" tabindex="0" role="button"src="/static/shared/icon/check_circle_gm_grey_24dp.svg" alt="checked" aria-label="Valid file, toggle tooltip"height="24" width="24"> Valid <a href="https://cs.opensource.google/go/go/+/go1.24.0:src/go.mod" target="_blank" rel="noopener">go.mod</a> file <img class="go-Icon" role="button" tabindex="0" src="/static/shared/icon/help_gm_grey_24dp.svg" alt="" aria-label="Toggle go.mod validity tooltip" height="24" width="24"> </summary> <p aria-live="polite" role="tooltip"> The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go. </p> </details> </li> <li> <details class="go-Tooltip js-tooltip" data-gtmc="tooltip"> <summary class="go-textSubtle"> <img class="go-Icon go-Icon--accented" tabindex="0" role="button"src="/static/shared/icon/check_circle_gm_grey_24dp.svg" alt="checked" aria-label="Valid file, toggle tooltip"height="24" width="24"> Redistributable license <img class="go-Icon" role="button" tabindex="0" src="/static/shared/icon/help_gm_grey_24dp.svg" alt="" aria-label="Toggle redistributable help tooltip" height="24" width="24"> </summary> <p aria-live="polite" role="tooltip"> Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed. </p> </details> </li> <li> <details class="go-Tooltip js-tooltip" data-gtmc="tooltip"> <summary class="go-textSubtle"> <img class="go-Icon go-Icon--accented" tabindex="0" role="button"src="/static/shared/icon/check_circle_gm_grey_24dp.svg" alt="checked" aria-label="Valid file, toggle tooltip"height="24" width="24"> Tagged version <img class="go-Icon" role="button" tabindex="0" src="/static/shared/icon/help_gm_grey_24dp.svg" alt="" aria-label="Toggle tagged version tooltip" height="24" width="24"> </summary> <p aria-live="polite" role="tooltip">Modules with tagged versions give importers more predictable builds.</p> </details> </li> <li> <details class="go-Tooltip js-tooltip" data-gtmc="tooltip"> <summary class="go-textSubtle"> <img class="go-Icon go-Icon--accented" tabindex="0" role="button"src="/static/shared/icon/check_circle_gm_grey_24dp.svg" alt="checked" aria-label="Valid file, toggle tooltip"height="24" width="24"> Stable version <img class="go-Icon" role="button" tabindex="0" aria-label="Toggle stable version tooltip" src="/static/shared/icon/help_gm_grey_24dp.svg" alt="" height="24" width="24"> </summary> <p aria-live="polite" role="tooltip">When a project reaches major version v1 it is considered stable.</p> </details> </li> <li class="UnitMeta-detailsLearn"> <a href="/about#best-practices" data-gtmc="meta link">Learn more about best practices</a> </li> </ul> <h2 class="go-textLabel">Repository</h2> <div class="UnitMeta-repo"> <a href="https://cs.opensource.google/go/go" title="https://cs.opensource.google/go/go" target="_blank" rel="noopener"> cs.opensource.google/go/go </a> </div> <h2 class="go-textLabel" data-test-id="links-heading">Links</h2> <ul class="UnitMeta-links"> <li> <a href="https://go.dev/security/policy" title="Report security issues in the Go standard library and sub-repositories"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/security_grey_24dp.svg" alt=""> Report a Vulnerability </a> </li> </ul> </div> </aside> <nav class="go-Main-nav go-Main-nav--sticky js-mainNav" aria-label="Outline"> <div class="go-Main-navDesktop"> <div class="UnitOutline-jumpTo"> <button class="UnitOutline-jumpToInput go-ShortcutKey js-jumpToInput" aria-controls="jump-to-modal" aria-label="Open Jump to Identifier" data-shortcut="f" data-shortcut-alt="find" data-test-id="jump-to-button" data-gtmc="outline button"> Jump to ... </button> </div> <ul class="go-Tree js-tree" role="tree" aria-label="Outline"> <li> <a href="#section-documentation" data-gtmc="outline link"> Documentation </a> <ul> <li> <a href="#pkg-overview" data-gtmc="doc outline link">Overview</a> </li> <li class="DocNav-overview"> <a href="#pkg-index" data-gtmc="doc outline link"> Index </a> <ul> <li> <a href="#pkg-examples" data-gtmc="doc outline link"> Examples </a> </li> </ul> </li> <li class="DocNav-constants"> <a href="#pkg-constants" data-gtmc="doc outline link"> Constants </a> </li> <li class="DocNav-variables"> <a href="#pkg-variables" data-gtmc="doc outline link"> Variables </a> </li> <li class="DocNav-functions"> <a href="#pkg-functions" data-gtmc="doc outline link"> Functions </a> <ul> <li> <a href="#HTMLEscape" title="HTMLEscape(w, b)" data-gtmc="doc outline link"> HTMLEscape(w, b) </a> </li> <li> <a href="#HTMLEscapeString" title="HTMLEscapeString(s)" data-gtmc="doc outline link"> HTMLEscapeString(s) </a> </li> <li> <a href="#HTMLEscaper" title="HTMLEscaper(args)" data-gtmc="doc outline link"> HTMLEscaper(args) </a> </li> <li> <a href="#IsTrue" title="IsTrue(val)" data-gtmc="doc outline link"> IsTrue(val) </a> </li> <li> <a href="#JSEscape" title="JSEscape(w, b)" data-gtmc="doc outline link"> JSEscape(w, b) </a> </li> <li> <a href="#JSEscapeString" title="JSEscapeString(s)" data-gtmc="doc outline link"> JSEscapeString(s) </a> </li> <li> <a href="#JSEscaper" title="JSEscaper(args)" data-gtmc="doc outline link"> JSEscaper(args) </a> </li> <li> <a href="#URLQueryEscaper" title="URLQueryEscaper(args)" data-gtmc="doc outline link"> URLQueryEscaper(args) </a> </li> </ul> </li> <li class="DocNav-types"> <a href="#pkg-types" data-gtmc="doc outline link"> Types </a> <ul> <li> <a href="#ExecError" title="type ExecError" data-gtmc="doc outline link"> type ExecError </a> <ul> <li> <a href="#ExecError.Error" title="(e) Error()" data-gtmc="doc outline link"> (e) Error() </a> </li> <li> <a href="#ExecError.Unwrap" title="(e) Unwrap()" data-gtmc="doc outline link"> (e) Unwrap() </a> </li> </ul> </li> <li> <a href="#FuncMap" title="type FuncMap" data-gtmc="doc outline link"> type FuncMap </a> </li> <li> <a href="#Template" title="type Template" data-gtmc="doc outline link"> type Template </a> <ul> <li> <a href="#Must" title="Must(t, err)" data-gtmc="doc outline link"> Must(t, err) </a> </li> <li> <a href="#New" title="New(name)" data-gtmc="doc outline link"> New(name) </a> </li> <li> <a href="#ParseFS" title="ParseFS(fsys, patterns)" data-gtmc="doc outline link"> ParseFS(fsys, patterns) </a> </li> <li> <a href="#ParseFiles" title="ParseFiles(filenames)" data-gtmc="doc outline link"> ParseFiles(filenames) </a> </li> <li> <a href="#ParseGlob" title="ParseGlob(pattern)" data-gtmc="doc outline link"> ParseGlob(pattern) </a> </li> <li> <a href="#Template.AddParseTree" title="(t) AddParseTree(name, tree)" data-gtmc="doc outline link"> (t) AddParseTree(name, tree) </a> </li> <li> <a href="#Template.Clone" title="(t) Clone()" data-gtmc="doc outline link"> (t) Clone() </a> </li> <li> <a href="#Template.DefinedTemplates" title="(t) DefinedTemplates()" data-gtmc="doc outline link"> (t) DefinedTemplates() </a> </li> <li> <a href="#Template.Delims" title="(t) Delims(left, right)" data-gtmc="doc outline link"> (t) Delims(left, right) </a> </li> <li> <a href="#Template.Execute" title="(t) Execute(wr, data)" data-gtmc="doc outline link"> (t) Execute(wr, data) </a> </li> <li> <a href="#Template.ExecuteTemplate" title="(t) ExecuteTemplate(wr, name, data)" data-gtmc="doc outline link"> (t) ExecuteTemplate(wr, name, data) </a> </li> <li> <a href="#Template.Funcs" title="(t) Funcs(funcMap)" data-gtmc="doc outline link"> (t) Funcs(funcMap) </a> </li> <li> <a href="#Template.Lookup" title="(t) Lookup(name)" data-gtmc="doc outline link"> (t) Lookup(name) </a> </li> <li> <a href="#Template.Name" title="(t) Name()" data-gtmc="doc outline link"> (t) Name() </a> </li> <li> <a href="#Template.New" title="(t) New(name)" data-gtmc="doc outline link"> (t) New(name) </a> </li> <li> <a href="#Template.Option" title="(t) Option(opt)" data-gtmc="doc outline link"> (t) Option(opt) </a> </li> <li> <a href="#Template.Parse" title="(t) Parse(text)" data-gtmc="doc outline link"> (t) Parse(text) </a> </li> <li> <a href="#Template.ParseFS" title="(t) ParseFS(fsys, patterns)" data-gtmc="doc outline link"> (t) ParseFS(fsys, patterns) </a> </li> <li> <a href="#Template.ParseFiles" title="(t) ParseFiles(filenames)" data-gtmc="doc outline link"> (t) ParseFiles(filenames) </a> </li> <li> <a href="#Template.ParseGlob" title="(t) ParseGlob(pattern)" data-gtmc="doc outline link"> (t) ParseGlob(pattern) </a> </li> <li> <a href="#Template.Templates" title="(t) Templates()" data-gtmc="doc outline link"> (t) Templates() </a> </li> </ul> </li> </ul> </li> </ul> </li> <li> <a href="#section-sourcefiles" data-gtmc="outline link"> Source Files </a> </li> <li> <a href="#section-directories" data-gtmc="outline link"> Directories </a> </li> </ul> </div> <div class="go-Main-navMobile js-mainNavMobile"> <label class="go-Label"> <select class="go-Select"> <option selected disabled>Documentation</option> </select> </label> </div> </nav> <article class="go-Main-article js-mainContent"> <div class="UnitDetails" data-test-id="UnitDetails" style="display: block;"> <div class="UnitDetails-content js-unitDetailsContent" data-test-id="UnitDetails-content"> <div class="UnitDoc"> <h2 class="UnitDoc-title" id="section-documentation"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/code_gm_grey_24dp.svg" alt=""> Documentation <a class="UnitDoc-idLink" href="#section-documentation" title="Go to Documentation" aria-label="Go to Documentation">露</a> </h2> <div class="Documentation js-documentation"> <div class="Documentation-content js-docContent"> <section class="Documentation-overview"> <h3 tabindex="-1" id="pkg-overview" class="Documentation-overviewHeader">Overview <a href="#pkg-overview" title="Go to Overview" aria-label="Go to Overview">露</a></h3> <div role="navigation" aria-label="Table of Contents"> <ul class="Documentation-toc Documentation-toc-columns"> <li class="Documentation-tocItem"><a href="#hdr-Text_and_spaces">Text and spaces</a></li> <li class="Documentation-tocItem"><a href="#hdr-Actions">Actions</a></li> <li class="Documentation-tocItem"><a href="#hdr-Arguments">Arguments</a></li> <li class="Documentation-tocItem"><a href="#hdr-Pipelines">Pipelines</a></li> <li class="Documentation-tocItem"><a href="#hdr-Variables">Variables</a></li> <li class="Documentation-tocItem"><a href="#hdr-Examples">Examples</a></li> <li class="Documentation-tocItem"><a href="#hdr-Functions">Functions</a></li> <li class="Documentation-tocItem"><a href="#hdr-Associated_templates">Associated templates</a></li> <li class="Documentation-tocItem"><a href="#hdr-Nested_template_definitions">Nested template definitions</a></li> </ul> </div> <p>Package template implements data-driven templates for generating textual output. </p><p>To generate HTML output, see <a href="/html/template">html/template</a>, which has the same interface as this package but automatically secures HTML output against certain attacks. </p><p>Templates are executed by applying them to a data structure. Annotations in the template refer to elements of the data structure (typically a field of a struct or a key in a map) to control execution and derive values to be displayed. Execution of the template walks the structure and sets the cursor, represented by a period '.' and called "dot", to the value at the current location in the structure as execution proceeds. </p><p>The input text for a template is UTF-8-encoded text in any format. "Actions"--data evaluations or control structures--are delimited by "{{" and "}}"; all text outside actions is copied to the output unchanged. </p><p>Once parsed, a template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved. </p><p>Here is a trivial example that prints "17 items are made of wool". </p><pre>type Inventory struct { Material string Count uint } sweaters := Inventory{"wool", 17} tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}") if err != nil { panic(err) } err = tmpl.Execute(os.Stdout, sweaters) if err != nil { panic(err) } </pre><p>More intricate examples appear below. </p><h4 id="hdr-Text_and_spaces">Text and spaces <a class="Documentation-idLink" href="#hdr-Text_and_spaces" title="Go to Text and spaces" aria-label="Go to Text and spaces">露</a></h4><p>By default, all text between actions is copied verbatim when the template is executed. For example, the string " items are made of " in the example above appears on standard output when the program is run. </p><p>However, to aid in formatting template source code, if an action's left delimiter (by default "{{") is followed immediately by a minus sign and white space, all trailing white space is trimmed from the immediately preceding text. Similarly, if the right delimiter ("}}") is preceded by white space and a minus sign, all leading white space is trimmed from the immediately following text. In these trim markers, the white space must be present: "{{- 3}}" is like "{{3}}" but trims the immediately preceding text, while "{{-3}}" parses as an action containing the number -3. </p><p>For instance, when executing the template whose source is </p><pre>"{{23 -}} < {{- 45}}" </pre><p>the generated output would be </p><pre>"23<45" </pre><p>For this trimming, the definition of white space characters is the same as in Go: space, horizontal tab, carriage return, and newline. </p><h4 id="hdr-Actions">Actions <a class="Documentation-idLink" href="#hdr-Actions" title="Go to Actions" aria-label="Go to Actions">露</a></h4><p>Here is the list of actions. "Arguments" and "pipelines" are evaluations of data, defined in detail in the corresponding sections that follow. </p><pre>{{/* a comment */}} {{- /* a comment with white space trimmed from preceding and following text */ -}} A comment; discarded. May contain newlines. Comments do not nest and must start and end at the delimiters, as shown here. {{pipeline}} The default textual representation (the same as would be printed by fmt.Print) of the value of the pipeline is copied to the output. {{if pipeline}} T1 {{end}} If the value of the pipeline is empty, no output is generated; otherwise, T1 is executed. The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. Dot is unaffected. {{if pipeline}} T1 {{else}} T0 {{end}} If the value of the pipeline is empty, T0 is executed; otherwise, T1 is executed. Dot is unaffected. {{if pipeline}} T1 {{else if pipeline}} T0 {{end}} To simplify the appearance of if-else chains, the else action of an if may include another if directly; the effect is exactly the same as writing {{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}} {{range pipeline}} T1 {{end}} The value of the pipeline must be an array, slice, map, iter.Seq, iter.Seq2, integer or channel. If the value of the pipeline has length zero, nothing is output; otherwise, dot is set to the successive elements of the array, slice, or map and T1 is executed. If the value is a map and the keys are of basic type with a defined order, the elements will be visited in sorted key order. {{range pipeline}} T1 {{else}} T0 {{end}} The value of the pipeline must be an array, slice, map, iter.Seq, iter.Seq2, integer or channel. If the value of the pipeline has length zero, dot is unaffected and T0 is executed; otherwise, dot is set to the successive elements of the array, slice, or map and T1 is executed. {{break}} The innermost {{range pipeline}} loop is ended early, stopping the current iteration and bypassing all remaining iterations. {{continue}} The current iteration of the innermost {{range pipeline}} loop is stopped, and the loop starts the next iteration. {{template "name"}} The template with the specified name is executed with nil data. {{template "name" pipeline}} The template with the specified name is executed with dot set to the value of the pipeline. {{block "name" pipeline}} T1 {{end}} A block is shorthand for defining a template {{define "name"}} T1 {{end}} and then executing it in place {{template "name" pipeline}} The typical use is to define a set of root templates that are then customized by redefining the block templates within. {{with pipeline}} T1 {{end}} If the value of the pipeline is empty, no output is generated; otherwise, dot is set to the value of the pipeline and T1 is executed. {{with pipeline}} T1 {{else}} T0 {{end}} If the value of the pipeline is empty, dot is unaffected and T0 is executed; otherwise, dot is set to the value of the pipeline and T1 is executed. {{with pipeline}} T1 {{else with pipeline}} T0 {{end}} To simplify the appearance of with-else chains, the else action of a with may include another with directly; the effect is exactly the same as writing {{with pipeline}} T1 {{else}}{{with pipeline}} T0 {{end}}{{end}} </pre><h4 id="hdr-Arguments">Arguments <a class="Documentation-idLink" href="#hdr-Arguments" title="Go to Arguments" aria-label="Go to Arguments">露</a></h4><p>An argument is a simple value, denoted by one of the following. </p><ul class="Documentation-bulletList"> <li><p>A boolean, string, character, integer, floating-point, imaginary or complex constant in Go syntax. These behave like Go's untyped constants. Note that, as in Go, whether a large integer constant overflows when assigned or passed to a function can depend on whether the host machine's ints are 32 or 64 bits. </p></li> <li><p>The keyword nil, representing an untyped Go nil. </p></li> <li><p>The character '.' (period): </p><p>. </p><p>The result is the value of dot. </p></li> <li><p>A variable name, which is a (possibly empty) alphanumeric string preceded by a dollar sign, such as </p><p>$piOver2 </p><p>or </p><p>$ </p><p>The result is the value of the variable. Variables are described below. </p></li> <li><p>The name of a field of the data, which must be a struct, preceded by a period, such as </p><p>.Field </p><p>The result is the value of the field. Field invocations may be chained: </p><p>.Field1.Field2 </p><p>Fields can also be evaluated on variables, including chaining: </p><p>$x.Field1.Field2 </p></li> <li><p>The name of a key of the data, which must be a map, preceded by a period, such as </p><p>.Key </p><p>The result is the map element value indexed by the key. Key invocations may be chained and combined with fields to any depth: </p><p>.Field1.Key1.Field2.Key2 </p><p>Although the key must be an alphanumeric identifier, unlike with field names they do not need to start with an upper case letter. Keys can also be evaluated on variables, including chaining: </p><p>$x.key1.key2 </p></li> <li><p>The name of a niladic method of the data, preceded by a period, such as </p><p>.Method </p><p>The result is the value of invoking the method with dot as the receiver, dot.Method(). Such a method must have one return value (of any type) or two return values, the second of which is an error. If it has two and the returned error is non-nil, execution terminates and an error is returned to the caller as the value of Execute. Method invocations may be chained and combined with fields and keys to any depth: </p><p>.Field1.Key1.Method1.Field2.Key2.Method2 </p><p>Methods can also be evaluated on variables, including chaining: </p><p>$x.Method1.Field </p></li> <li><p>The name of a niladic function, such as </p><p>fun </p><p>The result is the value of invoking the function, fun(). The return types and values behave as in methods. Functions and function names are described below. </p></li> <li><p>A parenthesized instance of one the above, for grouping. The result may be accessed by a field or map key invocation. </p><p>print (.F1 arg1) (.F2 arg2) (.StructValuedMethod "arg").Field </p></li> </ul><p>Arguments may evaluate to any type; if they are pointers the implementation automatically indirects to the base type when required. If an evaluation yields a function value, such as a function-valued field of a struct, the function is not invoked automatically, but it can be used as a truth value for an if action and the like. To invoke it, use the call function, defined below. </p><h4 id="hdr-Pipelines">Pipelines <a class="Documentation-idLink" href="#hdr-Pipelines" title="Go to Pipelines" aria-label="Go to Pipelines">露</a></h4><p>A pipeline is a possibly chained sequence of "commands". A command is a simple value (argument) or a function or method call, possibly with multiple arguments: </p><pre>Argument The result is the value of evaluating the argument. .Method [Argument...] The method can be alone or the last element of a chain but, unlike methods in the middle of a chain, it can take arguments. The result is the value of calling the method with the arguments: dot.Method(Argument1, etc.) functionName [Argument...] The result is the value of calling the function associated with the name: function(Argument1, etc.) Functions and function names are described below. </pre><p>A pipeline may be "chained" by separating a sequence of commands with pipeline characters '|'. In a chained pipeline, the result of each command is passed as the last argument of the following command. The output of the final command in the pipeline is the value of the pipeline. </p><p>The output of a command will be either one value or two values, the second of which has type error. If that second value is present and evaluates to non-nil, execution terminates and the error is returned to the caller of Execute. </p><h4 id="hdr-Variables">Variables <a class="Documentation-idLink" href="#hdr-Variables" title="Go to Variables" aria-label="Go to Variables">露</a></h4><p>A pipeline inside an action may initialize a variable to capture the result. The initialization has syntax </p><pre>$variable := pipeline </pre><p>where $variable is the name of the variable. An action that declares a variable produces no output. </p><p>Variables previously declared can also be assigned, using the syntax </p><pre>$variable = pipeline </pre><p>If a "range" action initializes a variable, the variable is set to the successive elements of the iteration. Also, a "range" may declare two variables, separated by a comma: </p><pre>range $index, $element := pipeline </pre><p>in which case $index and $element are set to the successive values of the array/slice index or map key and element, respectively. Note that if there is only one variable, it is assigned the element; this is opposite to the convention in Go range clauses. </p><p>A variable's scope extends to the "end" action of the control structure ("if", "with", or "range") in which it is declared, or to the end of the template if there is no such control structure. A template invocation does not inherit variables from the point of its invocation. </p><p>When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot. </p><h4 id="hdr-Examples">Examples <a class="Documentation-idLink" href="#hdr-Examples" title="Go to Examples" aria-label="Go to Examples">露</a></h4><p>Here are some example one-line templates demonstrating pipelines and variables. All produce the quoted word "output": </p><pre>{{"\"output\""}} A string constant. {{`"output"`}} A raw string constant. {{printf "%q" "output"}} A function call. {{"output" | printf "%q"}} A function call whose final argument comes from the previous command. {{printf "%q" (print "out" "put")}} A parenthesized argument. {{"put" | printf "%s%s" "out" | printf "%q"}} A more elaborate call. {{"output" | printf "%s" | printf "%q"}} A longer chain. {{with "output"}}{{printf "%q" .}}{{end}} A with action using dot. {{with $x := "output" | printf "%q"}}{{$x}}{{end}} A with action that creates and uses a variable. {{with $x := "output"}}{{printf "%q" $x}}{{end}} A with action that uses the variable in another action. {{with $x := "output"}}{{$x | printf "%q"}}{{end}} The same, but pipelined. </pre><h4 id="hdr-Functions">Functions <a class="Documentation-idLink" href="#hdr-Functions" title="Go to Functions" aria-label="Go to Functions">露</a></h4><p>During execution functions are found in two function maps: first in the template, then in the global function map. By default, no functions are defined in the template but the Funcs method can be used to add them. </p><p>Predefined global functions are named as follows. </p><pre>and Returns the boolean AND of its arguments by returning the first empty argument or the last argument. That is, "and x y" behaves as "if x then y else x." Evaluation proceeds through the arguments left to right and returns when the result is determined. call Returns the result of calling the first argument, which must be a function, with the remaining arguments as parameters. Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where Y is a func-valued field, map entry, or the like. The first argument must be the result of an evaluation that yields a value of function type (as distinct from a predefined function such as print). The function must return either one or two result values, the second of which is of type error. If the arguments don't match the function or the returned error value is non-nil, execution stops. html Returns the escaped HTML equivalent of the textual representation of its arguments. This function is unavailable in html/template, with a few exceptions. index Returns the result of indexing its first argument by the following arguments. Thus "index x 1 2 3" is, in Go syntax, x[1][2][3]. Each indexed item must be a map, slice, or array. slice slice returns the result of slicing its first argument by the remaining arguments. Thus "slice x 1 2" is, in Go syntax, x[1:2], while "slice x" is x[:], "slice x 1" is x[1:], and "slice x 1 2 3" is x[1:2:3]. The first argument must be a string, slice, or array. js Returns the escaped JavaScript equivalent of the textual representation of its arguments. len Returns the integer length of its argument. not Returns the boolean negation of its single argument. or Returns the boolean OR of its arguments by returning the first non-empty argument or the last argument, that is, "or x y" behaves as "if x then x else y". Evaluation proceeds through the arguments left to right and returns when the result is determined. print An alias for fmt.Sprint printf An alias for fmt.Sprintf println An alias for fmt.Sprintln urlquery Returns the escaped value of the textual representation of its arguments in a form suitable for embedding in a URL query. This function is unavailable in html/template, with a few exceptions. </pre><p>The boolean functions take any zero value to be false and a non-zero value to be true. </p><p>There is also a set of binary comparison operators defined as functions: </p><pre>eq Returns the boolean truth of arg1 == arg2 ne Returns the boolean truth of arg1 != arg2 lt Returns the boolean truth of arg1 < arg2 le Returns the boolean truth of arg1 <= arg2 gt Returns the boolean truth of arg1 > arg2 ge Returns the boolean truth of arg1 >= arg2 </pre><p>For simpler multi-way equality tests, eq (only) accepts two or more arguments and compares the second and subsequent to the first, returning in effect </p><pre>arg1==arg2 || arg1==arg3 || arg1==arg4 ... </pre><p>(Unlike with || in Go, however, eq is a function call and all the arguments will be evaluated.) </p><p>The comparison functions work on any values whose type Go defines as comparable. For basic types such as integers, the rules are relaxed: size and exact type are ignored, so any integer value, signed or unsigned, may be compared with any other integer value. (The arithmetic value is compared, not the bit pattern, so all negative integers are less than all unsigned integers.) However, as usual, one may not compare an int with a float32 and so on. </p><h4 id="hdr-Associated_templates">Associated templates <a class="Documentation-idLink" href="#hdr-Associated_templates" title="Go to Associated templates" aria-label="Go to Associated templates">露</a></h4><p>Each template is named by a string specified when it is created. Also, each template is associated with zero or more other templates that it may invoke by name; such associations are transitive and form a name space of templates. </p><p>A template may use a template invocation to instantiate another associated template; see the explanation of the "template" action above. The name must be that of a template associated with the template that contains the invocation. </p><h4 id="hdr-Nested_template_definitions">Nested template definitions <a class="Documentation-idLink" href="#hdr-Nested_template_definitions" title="Go to Nested template definitions" aria-label="Go to Nested template definitions">露</a></h4><p>When parsing a template, another template may be defined and associated with the template being parsed. Template definitions must appear at the top level of the template, much like global variables in a Go program. </p><p>The syntax of such definitions is to surround each template declaration with a "define" and "end" action. </p><p>The define action names the template being created by providing a string constant. Here is a simple example: </p><pre>{{define "T1"}}ONE{{end}} {{define "T2"}}TWO{{end}} {{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}} {{template "T3"}} </pre><p>This defines two templates, T1 and T2, and a third T3 that invokes the other two when it is executed. Finally it invokes T3. If executed this template will produce the text </p><pre>ONE TWO </pre><p>By construction, a template may reside in only one association. If it's necessary to have a template addressable from multiple associations, the template definition must be parsed multiple times to create distinct *Template values, or must be copied with <a href="#Template.Clone">Template.Clone</a> or <a href="#Template.AddParseTree">Template.AddParseTree</a>. </p><p>Parse may be called multiple times to assemble the various associated templates; see <a href="#ParseFiles">ParseFiles</a>, <a href="#ParseGlob">ParseGlob</a>, <a href="#Template.ParseFiles">Template.ParseFiles</a> and <a href="#Template.ParseGlob">Template.ParseGlob</a> for simple ways to parse related templates stored in files. </p><p>A template may be executed directly or through <a href="#Template.ExecuteTemplate">Template.ExecuteTemplate</a>, which executes an associated template identified by name. To invoke our example above, we might write, </p><pre>err := tmpl.Execute(os.Stdout, "no data needed") if err != nil { log.Fatalf("execution failed: %s", err) } </pre><p>or to invoke a particular template explicitly by name, </p><pre>err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed") if err != nil { log.Fatalf("execution failed: %s", err) } </pre> </section><section class="Documentation-index"> <h3 id="pkg-index" class="Documentation-indexHeader">Index <a href="#pkg-index" title="Go to Index" aria-label="Go to Index">露</a></h3> <ul class="Documentation-indexList"> <li class="Documentation-indexFunction"> <a href="#HTMLEscape">func HTMLEscape(w io.Writer, b []byte)</a></li> <li class="Documentation-indexFunction"> <a href="#HTMLEscapeString">func HTMLEscapeString(s string) string</a></li> <li class="Documentation-indexFunction"> <a href="#HTMLEscaper">func HTMLEscaper(args ...any) string</a></li> <li class="Documentation-indexFunction"> <a href="#IsTrue">func IsTrue(val any) (truth, ok bool)</a></li> <li class="Documentation-indexFunction"> <a href="#JSEscape">func JSEscape(w io.Writer, b []byte)</a></li> <li class="Documentation-indexFunction"> <a href="#JSEscapeString">func JSEscapeString(s string) string</a></li> <li class="Documentation-indexFunction"> <a href="#JSEscaper">func JSEscaper(args ...any) string</a></li> <li class="Documentation-indexFunction"> <a href="#URLQueryEscaper">func URLQueryEscaper(args ...any) string</a></li> <li class="Documentation-indexType"> <a href="#ExecError">type ExecError</a></li> <li><ul class="Documentation-indexTypeMethods"> <li> <a href="#ExecError.Error">func (e ExecError) Error() string</a></li> <li> <a href="#ExecError.Unwrap">func (e ExecError) Unwrap() error</a></li> </ul></li> <li class="Documentation-indexType"> <a href="#FuncMap">type FuncMap</a></li> <li class="Documentation-indexType"> <a href="#Template">type Template</a></li> <li><ul class="Documentation-indexTypeFunctions"> <li> <a href="#Must">func Must(t *Template, err error) *Template</a></li> <li> <a href="#New">func New(name string) *Template</a></li> <li> <a href="#ParseFS">func ParseFS(fsys fs.FS, patterns ...string) (*Template, error)</a></li> <li> <a href="#ParseFiles">func ParseFiles(filenames ...string) (*Template, error)</a></li> <li> <a href="#ParseGlob">func ParseGlob(pattern string) (*Template, error)</a></li> </ul></li> <li><ul class="Documentation-indexTypeMethods"> <li> <a href="#Template.AddParseTree">func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)</a></li> <li> <a href="#Template.Clone">func (t *Template) Clone() (*Template, error)</a></li> <li> <a href="#Template.DefinedTemplates">func (t *Template) DefinedTemplates() string</a></li> <li> <a href="#Template.Delims">func (t *Template) Delims(left, right string) *Template</a></li> <li> <a href="#Template.Execute">func (t *Template) Execute(wr io.Writer, data any) error</a></li> <li> <a href="#Template.ExecuteTemplate">func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error</a></li> <li> <a href="#Template.Funcs">func (t *Template) Funcs(funcMap FuncMap) *Template</a></li> <li> <a href="#Template.Lookup">func (t *Template) Lookup(name string) *Template</a></li> <li> <a href="#Template.Name">func (t *Template) Name() string</a></li> <li> <a href="#Template.New">func (t *Template) New(name string) *Template</a></li> <li> <a href="#Template.Option">func (t *Template) Option(opt ...string) *Template</a></li> <li> <a href="#Template.Parse">func (t *Template) Parse(text string) (*Template, error)</a></li> <li> <a href="#Template.ParseFS">func (t *Template) ParseFS(fsys fs.FS, patterns ...string) (*Template, error)</a></li> <li> <a href="#Template.ParseFiles">func (t *Template) ParseFiles(filenames ...string) (*Template, error)</a></li> <li> <a href="#Template.ParseGlob">func (t *Template) ParseGlob(pattern string) (*Template, error)</a></li> <li> <a href="#Template.Templates">func (t *Template) Templates() []*Template</a></li> </ul></li> </ul> </section><section class="Documentation-examples"> <h4 tabindex="-1" id="pkg-examples" class="Documentation-examplesHeader">Examples <a class="Documentation-idLink" href="#pkg-examples" title="Go to Examples" aria-label="Go to Examples">露</a></h4> <ul class="Documentation-examplesList"> <li><a href="#example-Template" class="js-exampleHref">Template</a></li> <li><a href="#example-Template-Block" class="js-exampleHref">Template (Block)</a></li> <li><a href="#example-Template-Func" class="js-exampleHref">Template (Func)</a></li> <li><a href="#example-Template-Glob" class="js-exampleHref">Template (Glob)</a></li> <li><a href="#example-Template-Helpers" class="js-exampleHref">Template (Helpers)</a></li> <li><a href="#example-Template-Share" class="js-exampleHref">Template (Share)</a></li> </ul> </section><h3 tabindex="-1" id="pkg-constants" class="Documentation-constantsHeader">Constants <a href="#pkg-constants" title="Go to Constants" aria-label="Go to Constants">露</a></h3> <section class="Documentation-constants"><p class="Documentation-empty">This section is empty.</p></section> <h3 tabindex="-1" id="pkg-variables" class="Documentation-variablesHeader">Variables <a href="#pkg-variables" title="Go to Variables" aria-label="Go to Variables">露</a></h3> <section class="Documentation-variables"><p class="Documentation-empty">This section is empty.</p></section> <h3 tabindex="-1" id="pkg-functions" class="Documentation-functionsHeader">Functions <a href="#pkg-functions" title="Go to Functions" aria-label="Go to Functions">露</a></h3> <section class="Documentation-functions"><div class="Documentation-function"> <h4 tabindex="-1" id="HTMLEscape" data-kind="function" class="Documentation-functionHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/funcs.go;l=619">HTMLEscape</a> <a class="Documentation-idLink" href="#HTMLEscape" title="Go to HTMLEscape" aria-label="Go to HTMLEscape">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func HTMLEscape(w <a href="/io">io</a>.<a href="/io#Writer">Writer</a>, b []<a href="/builtin#byte">byte</a>)</pre> </div> <p>HTMLEscape writes to w the escaped HTML equivalent of the plain text data b. </p> </div><div class="Documentation-function"> <h4 tabindex="-1" id="HTMLEscapeString" data-kind="function" class="Documentation-functionHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/funcs.go;l=647">HTMLEscapeString</a> <a class="Documentation-idLink" href="#HTMLEscapeString" title="Go to HTMLEscapeString" aria-label="Go to HTMLEscapeString">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func HTMLEscapeString(s <a href="/builtin#string">string</a>) <a href="/builtin#string">string</a></pre> </div> <p>HTMLEscapeString returns the escaped HTML equivalent of the plain text data s. </p> </div><div class="Documentation-function"> <h4 tabindex="-1" id="HTMLEscaper" data-kind="function" class="Documentation-functionHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/funcs.go;l=659">HTMLEscaper</a> <a class="Documentation-idLink" href="#HTMLEscaper" title="Go to HTMLEscaper" aria-label="Go to HTMLEscaper">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func HTMLEscaper(args ...<a href="/builtin#any">any</a>) <a href="/builtin#string">string</a></pre> </div> <p>HTMLEscaper returns the escaped HTML equivalent of the textual representation of its arguments. </p> </div><div class="Documentation-function"> <h4 tabindex="-1" id="IsTrue" data-kind="function" class="Documentation-functionHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/exec.go;l=320">IsTrue</a> <a class="Documentation-idLink" href="#IsTrue" title="Go to IsTrue" aria-label="Go to IsTrue">露</a></span> <span class="Documentation-sinceVersion"> <span class="Documentation-sinceVersionLabel">added in</span> <span class="Documentation-sinceVersionVersion">go1.6</span> </span> </h4> <div class="Documentation-declaration"> <pre>func IsTrue(val <a href="/builtin#any">any</a>) (truth, ok <a href="/builtin#bool">bool</a>)</pre> </div> <p>IsTrue reports whether the value is 'true', in the sense of not the zero of its type, and whether the value has a meaningful truth value. This is the definition of truth used by if and other such actions. </p> </div><div class="Documentation-function"> <h4 tabindex="-1" id="JSEscape" data-kind="function" class="Documentation-functionHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/funcs.go;l=679">JSEscape</a> <a class="Documentation-idLink" href="#JSEscape" title="Go to JSEscape" aria-label="Go to JSEscape">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func JSEscape(w <a href="/io">io</a>.<a href="/io#Writer">Writer</a>, b []<a href="/builtin#byte">byte</a>)</pre> </div> <p>JSEscape writes to w the escaped JavaScript equivalent of the plain text data b. </p> </div><div class="Documentation-function"> <h4 tabindex="-1" id="JSEscapeString" data-kind="function" class="Documentation-functionHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/funcs.go;l=730">JSEscapeString</a> <a class="Documentation-idLink" href="#JSEscapeString" title="Go to JSEscapeString" aria-label="Go to JSEscapeString">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func JSEscapeString(s <a href="/builtin#string">string</a>) <a href="/builtin#string">string</a></pre> </div> <p>JSEscapeString returns the escaped JavaScript equivalent of the plain text data s. </p> </div><div class="Documentation-function"> <h4 tabindex="-1" id="JSEscaper" data-kind="function" class="Documentation-functionHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/funcs.go;l=750">JSEscaper</a> <a class="Documentation-idLink" href="#JSEscaper" title="Go to JSEscaper" aria-label="Go to JSEscaper">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func JSEscaper(args ...<a href="/builtin#any">any</a>) <a href="/builtin#string">string</a></pre> </div> <p>JSEscaper returns the escaped JavaScript equivalent of the textual representation of its arguments. </p> </div><div class="Documentation-function"> <h4 tabindex="-1" id="URLQueryEscaper" data-kind="function" class="Documentation-functionHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/funcs.go;l=756">URLQueryEscaper</a> <a class="Documentation-idLink" href="#URLQueryEscaper" title="Go to URLQueryEscaper" aria-label="Go to URLQueryEscaper">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func URLQueryEscaper(args ...<a href="/builtin#any">any</a>) <a href="/builtin#string">string</a></pre> </div> <p>URLQueryEscaper returns the escaped value of the textual representation of its arguments in a form suitable for embedding in a URL query. </p> </div></section> <h3 tabindex="-1" id="pkg-types" class="Documentation-typesHeader">Types <a href="#pkg-types" title="Go to Types" aria-label="Go to Types">露</a></h3> <section class="Documentation-types"><div class="Documentation-type"> <h4 tabindex="-1" id="ExecError" data-kind="type" class="Documentation-typeHeader"> <span>type <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/exec.go;l=121">ExecError</a> <a class="Documentation-idLink" href="#ExecError" title="Go to ExecError" aria-label="Go to ExecError">露</a></span> <span class="Documentation-sinceVersion"> <span class="Documentation-sinceVersionLabel">added in</span> <span class="Documentation-sinceVersionVersion">go1.6</span> </span> </h4> <div class="Documentation-declaration"> <pre>type ExecError struct { <span id="ExecError.Name" data-kind="field"> Name <a href="/builtin#string">string</a> <span class="comment">// Name of template.</span> </span><span id="ExecError.Err" data-kind="field"> Err <a href="/builtin#error">error</a> <span class="comment">// Pre-formatted error.</span> </span>}</pre> </div> <p>ExecError is the custom error type returned when Execute has an error evaluating its template. (If a write error occurs, the actual error is returned; it will not be of type ExecError.) </p> <div class="Documentation-typeMethod"> <h4 tabindex="-1" id="ExecError.Error" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (ExecError) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/exec.go;l=126">Error</a> <a class="Documentation-idLink" href="#ExecError.Error" title="Go to ExecError.Error" aria-label="Go to ExecError.Error">露</a></span> <span class="Documentation-sinceVersion"> <span class="Documentation-sinceVersionLabel">added in</span> <span class="Documentation-sinceVersionVersion">go1.6</span> </span> </h4> <div class="Documentation-declaration"> <pre>func (e <a href="#ExecError">ExecError</a>) Error() <a href="/builtin#string">string</a></pre> </div> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="ExecError.Unwrap" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (ExecError) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/exec.go;l=130">Unwrap</a> <a class="Documentation-idLink" href="#ExecError.Unwrap" title="Go to ExecError.Unwrap" aria-label="Go to ExecError.Unwrap">露</a></span> <span class="Documentation-sinceVersion"> <span class="Documentation-sinceVersionLabel">added in</span> <span class="Documentation-sinceVersionVersion">go1.13</span> </span> </h4> <div class="Documentation-declaration"> <pre>func (e <a href="#ExecError">ExecError</a>) Unwrap() <a href="/builtin#error">error</a></pre> </div> </div> </div><div class="Documentation-type"> <h4 tabindex="-1" id="FuncMap" data-kind="type" class="Documentation-typeHeader"> <span>type <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/funcs.go;l=33">FuncMap</a> <a class="Documentation-idLink" href="#FuncMap" title="Go to FuncMap" aria-label="Go to FuncMap">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>type FuncMap map[<a href="/builtin#string">string</a>]<a href="/builtin#any">any</a></pre> </div> <p>FuncMap is the type of the map defining the mapping from names to functions. Each function must have either a single return value, or two return values of which the second has type error. In that case, if the second (error) return value evaluates to non-nil during execution, execution terminates and Execute returns that error. </p><p>Errors returned by Execute wrap the underlying error; call <a href="/errors#As">errors.As</a> to unwrap them. </p><p>When template execution invokes a function with an argument list, that list must be assignable to the function's parameter types. Functions meant to apply to arguments of arbitrary type can use parameters of type interface{} or of type <a href="/reflect#Value">reflect.Value</a>. Similarly, functions meant to return a result of arbitrary type can return interface{} or <a href="/reflect#Value">reflect.Value</a>. </p> </div><div class="Documentation-type"> <h4 tabindex="-1" id="Template" data-kind="type" class="Documentation-typeHeader"> <span>type <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go;l=30">Template</a> <a class="Documentation-idLink" href="#Template" title="Go to Template" aria-label="Go to Template">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>type Template struct { <span id="Template.Tree" data-kind="field"> *<a href="/text/template/parse">parse</a>.<a href="/text/template/parse#Tree">Tree</a> </span> <span class="comment">// contains filtered or unexported fields</span> }</pre> </div> <p>Template is the representation of a parsed template. The *parse.Tree field is exported only for use by <a href="/html/template">html/template</a> and should be treated as unexported by all other clients. </p> <details tabindex="-1" id="example-Template" class="Documentation-exampleDetails js-exampleContainer"> <summary class="Documentation-exampleDetailsHeader">Example <a href="#example-Template" title="Go to Example" aria-label="Go to Example">露</a></summary> <div class="Documentation-exampleDetailsBody"> <pre class="Documentation-exampleCode"> package main import ( "log" "os" "text/template" ) func main() { // Define a template. const letter = ` Dear {{.Name}}, {{if .Attended}} It was a pleasure to see you at the wedding. {{- else}} It is a shame you couldn't make it to the wedding. {{- end}} {{with .Gift -}} Thank you for the lovely {{.}}. {{end}} Best wishes, Josie ` // Prepare some data to insert into the template. type Recipient struct { Name, Gift string Attended bool } var recipients = []Recipient{ {"Aunt Mildred", "bone china tea set", true}, {"Uncle John", "moleskin pants", false}, {"Cousin Rodney", "", false}, } // Create a new template and parse the letter into it. t := template.Must(template.New("letter").Parse(letter)) // Execute the template for each recipient. for _, r := range recipients { err := t.Execute(os.Stdout, r) if err != nil { log.Println("executing template:", err) } } } </pre> <pre><span class="Documentation-exampleOutputLabel">Output:</span> <span class="Documentation-exampleOutput">Dear Aunt Mildred, It was a pleasure to see you at the wedding. Thank you for the lovely bone china tea set. Best wishes, Josie Dear Uncle John, It is a shame you couldn't make it to the wedding. Thank you for the lovely moleskin pants. Best wishes, Josie Dear Cousin Rodney, It is a shame you couldn't make it to the wedding. Best wishes, Josie </span></pre> </div> <div class="Documentation-exampleButtonsContainer"> <p class="Documentation-exampleError" role="alert" aria-atomic="true"></p> <button class="Documentation-exampleShareButton" aria-label="Share Code">Share</button> <button class="Documentation-exampleFormatButton" aria-label="Format Code">Format</button> <button class="Documentation-exampleRunButton" aria-label="Run Code">Run</button> </div></details> <details tabindex="-1" id="example-Template-Block" class="Documentation-exampleDetails js-exampleContainer"> <summary class="Documentation-exampleDetailsHeader">Example (Block) <a href="#example-Template-Block" title="Go to Example (Block)" aria-label="Go to Example (Block)">露</a></summary> <div class="Documentation-exampleDetailsBody"> <pre class="Documentation-exampleCode"> package main import ( "log" "os" "strings" "text/template" ) func main() { const ( master = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}` overlay = `{{define "list"}} {{join . ", "}}{{end}} ` ) var ( funcs = template.FuncMap{"join": strings.Join} guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"} ) masterTmpl, err := template.New("master").Funcs(funcs).Parse(master) if err != nil { log.Fatal(err) } overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay) if err != nil { log.Fatal(err) } if err := masterTmpl.Execute(os.Stdout, guardians); err != nil { log.Fatal(err) } if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil { log.Fatal(err) } } </pre> <pre><span class="Documentation-exampleOutputLabel">Output:</span> <span class="Documentation-exampleOutput">Names: - Gamora - Groot - Nebula - Rocket - Star-Lord Names: Gamora, Groot, Nebula, Rocket, Star-Lord </span></pre> </div> <div class="Documentation-exampleButtonsContainer"> <p class="Documentation-exampleError" role="alert" aria-atomic="true"></p> <button class="Documentation-exampleShareButton" aria-label="Share Code">Share</button> <button class="Documentation-exampleFormatButton" aria-label="Format Code">Format</button> <button class="Documentation-exampleRunButton" aria-label="Run Code">Run</button> </div></details> <details tabindex="-1" id="example-Template-Func" class="Documentation-exampleDetails js-exampleContainer"> <summary class="Documentation-exampleDetailsHeader">Example (Func) <a href="#example-Template-Func" title="Go to Example (Func)" aria-label="Go to Example (Func)">露</a></summary> <div class="Documentation-exampleDetailsBody"> <p>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. </p> <pre class="Documentation-exampleCode"> package main import ( "log" "os" "strings" "text/template" ) func main() { // 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) } } </pre> <pre><span class="Documentation-exampleOutputLabel">Output:</span> <span class="Documentation-exampleOutput">Input: "the go programming language" Output 0: The Go Programming Language Output 1: "The Go Programming Language" Output 2: "The Go Programming Language" </span></pre> </div> <div class="Documentation-exampleButtonsContainer"> <p class="Documentation-exampleError" role="alert" aria-atomic="true"></p> <button class="Documentation-exampleShareButton" aria-label="Share Code">Share</button> <button class="Documentation-exampleFormatButton" aria-label="Format Code">Format</button> <button class="Documentation-exampleRunButton" aria-label="Run Code">Run</button> </div></details> <details tabindex="-1" id="example-Template-Glob" class="Documentation-exampleDetails js-exampleContainer"> <summary class="Documentation-exampleDetailsHeader">Example (Glob) <a href="#example-Template-Glob" title="Go to Example (Glob)" aria-label="Go to Example (Glob)">露</a></summary> <div class="Documentation-exampleDetailsBody"> <p>Here we demonstrate loading a set of templates from a directory. </p> <pre class="Documentation-exampleCode"> package main import ( "io" "log" "os" "path/filepath" "text/template" ) // templateFile defines the contents of a template to be stored in a file, for testing. type templateFile struct { name string contents string } func createTestDir(files []templateFile) string { dir, err := os.MkdirTemp("", "template") if err != nil { log.Fatal(err) } for _, file := range files { f, err := os.Create(filepath.Join(dir, file.name)) if err != nil { log.Fatal(err) } defer f.Close() _, err = io.WriteString(f, file.contents) if err != nil { log.Fatal(err) } } return dir } func main() { // Here we create a temporary directory and populate it with our sample // template definition files; usually the template files would already // exist in some location known to the program. dir := createTestDir([]templateFile{ // T0.tmpl is a plain template file that just invokes T1. {"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`}, // T1.tmpl defines a template, T1 that invokes T2. {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`}, // T2.tmpl defines a template T2. {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`}, }) // Clean up after the test; another quirk of running as an example. defer os.RemoveAll(dir) // pattern is the glob pattern used to find all the template files. pattern := filepath.Join(dir, "*.tmpl") // Here starts the example proper. // T0.tmpl is the first name matched, so it becomes the starting template, // the value returned by ParseGlob. tmpl := template.Must(template.ParseGlob(pattern)) err := tmpl.Execute(os.Stdout, nil) if err != nil { log.Fatalf("template execution: %s", err) } } </pre> <pre><span class="Documentation-exampleOutputLabel">Output:</span> <span class="Documentation-exampleOutput">T0 invokes T1: (T1 invokes T2: (This is T2)) </span></pre> </div> <div class="Documentation-exampleButtonsContainer"> <p class="Documentation-exampleError" role="alert" aria-atomic="true"></p> <button class="Documentation-exampleShareButton" aria-label="Share Code">Share</button> <button class="Documentation-exampleFormatButton" aria-label="Format Code">Format</button> <button class="Documentation-exampleRunButton" aria-label="Run Code">Run</button> </div></details> <details tabindex="-1" id="example-Template-Helpers" class="Documentation-exampleDetails js-exampleContainer"> <summary class="Documentation-exampleDetailsHeader">Example (Helpers) <a href="#example-Template-Helpers" title="Go to Example (Helpers)" aria-label="Go to Example (Helpers)">露</a></summary> <div class="Documentation-exampleDetailsBody"> <p>This example demonstrates one way to share some templates and use them in different contexts. In this variant we add multiple driver templates by hand to an existing bundle of templates. </p> <pre class="Documentation-exampleCode"> package main import ( "io" "log" "os" "path/filepath" "text/template" ) // templateFile defines the contents of a template to be stored in a file, for testing. type templateFile struct { name string contents string } func createTestDir(files []templateFile) string { dir, err := os.MkdirTemp("", "template") if err != nil { log.Fatal(err) } for _, file := range files { f, err := os.Create(filepath.Join(dir, file.name)) if err != nil { log.Fatal(err) } defer f.Close() _, err = io.WriteString(f, file.contents) if err != nil { log.Fatal(err) } } return dir } func main() { // Here we create a temporary directory and populate it with our sample // template definition files; usually the template files would already // exist in some location known to the program. dir := createTestDir([]templateFile{ // T1.tmpl defines a template, T1 that invokes T2. {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`}, // T2.tmpl defines a template T2. {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`}, }) // Clean up after the test; another quirk of running as an example. defer os.RemoveAll(dir) // pattern is the glob pattern used to find all the template files. pattern := filepath.Join(dir, "*.tmpl") // Here starts the example proper. // Load the helpers. templates := template.Must(template.ParseGlob(pattern)) // Add one driver template to the bunch; we do this with an explicit template definition. _, err := templates.Parse("{{define `driver1`}}Driver 1 calls T1: ({{template `T1`}})\n{{end}}") if err != nil { log.Fatal("parsing driver1: ", err) } // Add another driver template. _, err = templates.Parse("{{define `driver2`}}Driver 2 calls T2: ({{template `T2`}})\n{{end}}") if err != nil { log.Fatal("parsing driver2: ", err) } // We load all the templates before execution. This package does not require // that behavior but html/template's escaping does, so it's a good habit. err = templates.ExecuteTemplate(os.Stdout, "driver1", nil) if err != nil { log.Fatalf("driver1 execution: %s", err) } err = templates.ExecuteTemplate(os.Stdout, "driver2", nil) if err != nil { log.Fatalf("driver2 execution: %s", err) } } </pre> <pre><span class="Documentation-exampleOutputLabel">Output:</span> <span class="Documentation-exampleOutput">Driver 1 calls T1: (T1 invokes T2: (This is T2)) Driver 2 calls T2: (This is T2) </span></pre> </div> <div class="Documentation-exampleButtonsContainer"> <p class="Documentation-exampleError" role="alert" aria-atomic="true"></p> <button class="Documentation-exampleShareButton" aria-label="Share Code">Share</button> <button class="Documentation-exampleFormatButton" aria-label="Format Code">Format</button> <button class="Documentation-exampleRunButton" aria-label="Run Code">Run</button> </div></details> <details tabindex="-1" id="example-Template-Share" class="Documentation-exampleDetails js-exampleContainer"> <summary class="Documentation-exampleDetailsHeader">Example (Share) <a href="#example-Template-Share" title="Go to Example (Share)" aria-label="Go to Example (Share)">露</a></summary> <div class="Documentation-exampleDetailsBody"> <p>This example demonstrates how to use one group of driver templates with distinct sets of helper templates. </p> <pre class="Documentation-exampleCode"> package main import ( "io" "log" "os" "path/filepath" "text/template" ) // templateFile defines the contents of a template to be stored in a file, for testing. type templateFile struct { name string contents string } func createTestDir(files []templateFile) string { dir, err := os.MkdirTemp("", "template") if err != nil { log.Fatal(err) } for _, file := range files { f, err := os.Create(filepath.Join(dir, file.name)) if err != nil { log.Fatal(err) } defer f.Close() _, err = io.WriteString(f, file.contents) if err != nil { log.Fatal(err) } } return dir } func main() { // Here we create a temporary directory and populate it with our sample // template definition files; usually the template files would already // exist in some location known to the program. dir := createTestDir([]templateFile{ // T0.tmpl is a plain template file that just invokes T1. {"T0.tmpl", "T0 ({{.}} version) invokes T1: ({{template `T1`}})\n"}, // T1.tmpl defines a template, T1 that invokes T2. Note T2 is not defined {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`}, }) // Clean up after the test; another quirk of running as an example. defer os.RemoveAll(dir) // pattern is the glob pattern used to find all the template files. pattern := filepath.Join(dir, "*.tmpl") // Here starts the example proper. // Load the drivers. drivers := template.Must(template.ParseGlob(pattern)) // We must define an implementation of the T2 template. First we clone // the drivers, then add a definition of T2 to the template name space. // 1. Clone the helper set to create a new name space from which to run them. first, err := drivers.Clone() if err != nil { log.Fatal("cloning helpers: ", err) } // 2. Define T2, version A, and parse it. _, err = first.Parse("{{define `T2`}}T2, version A{{end}}") if err != nil { log.Fatal("parsing T2: ", err) } // Now repeat the whole thing, using a different version of T2. // 1. Clone the drivers. second, err := drivers.Clone() if err != nil { log.Fatal("cloning drivers: ", err) } // 2. Define T2, version B, and parse it. _, err = second.Parse("{{define `T2`}}T2, version B{{end}}") if err != nil { log.Fatal("parsing T2: ", err) } // Execute the templates in the reverse order to verify the // first is unaffected by the second. err = second.ExecuteTemplate(os.Stdout, "T0.tmpl", "second") if err != nil { log.Fatalf("second execution: %s", err) } err = first.ExecuteTemplate(os.Stdout, "T0.tmpl", "first") if err != nil { log.Fatalf("first: execution: %s", err) } } </pre> <pre><span class="Documentation-exampleOutputLabel">Output:</span> <span class="Documentation-exampleOutput">T0 (second version) invokes T1: (T1 invokes T2: (T2, version B)) T0 (first version) invokes T1: (T1 invokes T2: (T2, version A)) </span></pre> </div> <div class="Documentation-exampleButtonsContainer"> <p class="Documentation-exampleError" role="alert" aria-atomic="true"></p> <button class="Documentation-exampleShareButton" aria-label="Share Code">Share</button> <button class="Documentation-exampleFormatButton" aria-label="Format Code">Format</button> <button class="Documentation-exampleRunButton" aria-label="Run Code">Run</button> </div></details> <div class="Documentation-typeFunc"> <h4 tabindex="-1" id="Must" data-kind="function" class="Documentation-typeFuncHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/helper.go;l=24">Must</a> <a class="Documentation-idLink" href="#Must" title="Go to Must" aria-label="Go to Must">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func Must(t *<a href="#Template">Template</a>, err <a href="/builtin#error">error</a>) *<a href="#Template">Template</a></pre> </div> <p>Must is a helper that wraps a call to a function returning (<a href="#Template">*Template</a>, error) and panics if the error is non-nil. It is intended for use in variable initializations such as </p><pre>var t = template.Must(template.New("name").Parse("text")) </pre> </div><div class="Documentation-typeFunc"> <h4 tabindex="-1" id="New" data-kind="function" class="Documentation-typeFuncHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go;l=39">New</a> <a class="Documentation-idLink" href="#New" title="Go to New" aria-label="Go to New">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func New(name <a href="/builtin#string">string</a>) *<a href="#Template">Template</a></pre> </div> <p>New allocates a new, undefined template with the given name. </p> </div><div class="Documentation-typeFunc"> <h4 tabindex="-1" id="ParseFS" data-kind="function" class="Documentation-typeFuncHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/helper.go;l=138">ParseFS</a> <a class="Documentation-idLink" href="#ParseFS" title="Go to ParseFS" aria-label="Go to ParseFS">露</a></span> <span class="Documentation-sinceVersion"> <span class="Documentation-sinceVersionLabel">added in</span> <span class="Documentation-sinceVersionVersion">go1.16</span> </span> </h4> <div class="Documentation-declaration"> <pre>func ParseFS(fsys <a href="/io/fs">fs</a>.<a href="/io/fs#FS">FS</a>, patterns ...<a href="/builtin#string">string</a>) (*<a href="#Template">Template</a>, <a href="/builtin#error">error</a>)</pre> </div> <p>ParseFS is like <a href="#Template.ParseFiles">Template.ParseFiles</a> or <a href="#Template.ParseGlob">Template.ParseGlob</a> but reads from the file system fsys instead of the host operating system's file system. It accepts a list of glob patterns (see <a href="/path#Match">path.Match</a>). (Note that most file names serve as glob patterns matching only themselves.) </p> </div><div class="Documentation-typeFunc"> <h4 tabindex="-1" id="ParseFiles" data-kind="function" class="Documentation-typeFuncHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/helper.go;l=40">ParseFiles</a> <a class="Documentation-idLink" href="#ParseFiles" title="Go to ParseFiles" aria-label="Go to ParseFiles">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func ParseFiles(filenames ...<a href="/builtin#string">string</a>) (*<a href="#Template">Template</a>, <a href="/builtin#error">error</a>)</pre> </div> <p>ParseFiles creates a new <a href="#Template">Template</a> and parses the template definitions from the named files. The returned template's name will have the base name and parsed contents of the first file. There must be at least one file. If an error occurs, parsing stops and the returned *Template is nil. </p><p>When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template named "foo", while "a/foo" is unavailable. </p> </div><div class="Documentation-typeFunc"> <h4 tabindex="-1" id="ParseGlob" data-kind="function" class="Documentation-typeFuncHeader"> <span>func <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/helper.go;l=105">ParseGlob</a> <a class="Documentation-idLink" href="#ParseGlob" title="Go to ParseGlob" aria-label="Go to ParseGlob">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func ParseGlob(pattern <a href="/builtin#string">string</a>) (*<a href="#Template">Template</a>, <a href="/builtin#error">error</a>)</pre> </div> <p>ParseGlob creates a new <a href="#Template">Template</a> and parses the template definitions from the files identified by the pattern. The files are matched according to the semantics of <a href="/path/filepath#Match">filepath.Match</a>, and the pattern must match at least one file. The returned template will have the <a href="/path/filepath#Base">filepath.Base</a> name and (parsed) contents of the first file matched by the pattern. ParseGlob is equivalent to calling <a href="#ParseFiles">ParseFiles</a> with the list of files matched by the pattern. </p><p>When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.AddParseTree" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go;l=126">AddParseTree</a> <a class="Documentation-idLink" href="#Template.AddParseTree" title="Go to Template.AddParseTree" aria-label="Go to Template.AddParseTree">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) AddParseTree(name <a href="/builtin#string">string</a>, tree *<a href="/text/template/parse">parse</a>.<a href="/text/template/parse#Tree">Tree</a>) (*<a href="#Template">Template</a>, <a href="/builtin#error">error</a>)</pre> </div> <p>AddParseTree associates the argument parse tree with the template t, giving it the specified name. If the template has not been defined, this tree becomes its definition. If it has been defined and already has that name, the existing definition is replaced; otherwise a new template is created, defined, and returned. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.Clone" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go;l=87">Clone</a> <a class="Documentation-idLink" href="#Template.Clone" title="Go to Template.Clone" aria-label="Go to Template.Clone">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) Clone() (*<a href="#Template">Template</a>, <a href="/builtin#error">error</a>)</pre> </div> <p>Clone returns a duplicate of the template, including all associated templates. The actual representation is not copied, but the name space of associated templates is, so further calls to <a href="#Template.Parse">Template.Parse</a> in the copy will add templates to the copy but not to the original. Clone can be used to prepare common templates and use them with variant definitions for other templates by adding the variants after the clone is made. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.DefinedTemplates" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/exec.go;l=232">DefinedTemplates</a> <a class="Documentation-idLink" href="#Template.DefinedTemplates" title="Go to Template.DefinedTemplates" aria-label="Go to Template.DefinedTemplates">露</a></span> <span class="Documentation-sinceVersion"> <span class="Documentation-sinceVersionLabel">added in</span> <span class="Documentation-sinceVersionVersion">go1.5</span> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) DefinedTemplates() <a href="/builtin#string">string</a></pre> </div> <p>DefinedTemplates returns a string listing the defined templates, prefixed by the string "; defined templates are: ". If there are none, it returns the empty string. For generating an error message here and in <a href="/html/template">html/template</a>. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.Delims" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go;l=161">Delims</a> <a class="Documentation-idLink" href="#Template.Delims" title="Go to Template.Delims" aria-label="Go to Template.Delims">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) Delims(left, right <a href="/builtin#string">string</a>) *<a href="#Template">Template</a></pre> </div> <p>Delims sets the action delimiters to the specified strings, to be used in subsequent calls to <a href="#Template.Parse">Template.Parse</a>, <a href="#Template.ParseFiles">Template.ParseFiles</a>, or <a href="#Template.ParseGlob">Template.ParseGlob</a>. Nested template definitions will inherit the settings. An empty delimiter stands for the corresponding default: {{ or }}. The return value is the template, so calls can be chained. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.Execute" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/exec.go;l=206">Execute</a> <a class="Documentation-idLink" href="#Template.Execute" title="Go to Template.Execute" aria-label="Go to Template.Execute">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) Execute(wr <a href="/io">io</a>.<a href="/io#Writer">Writer</a>, data <a href="/builtin#any">any</a>) <a href="/builtin#error">error</a></pre> </div> <p>Execute applies a parsed template to the specified data object, and writes the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved. </p><p>If data is a <a href="/reflect#Value">reflect.Value</a>, the template applies to the concrete value that the reflect.Value holds, as in <a href="/fmt#Print">fmt.Print</a>. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.ExecuteTemplate" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/exec.go;l=188">ExecuteTemplate</a> <a class="Documentation-idLink" href="#Template.ExecuteTemplate" title="Go to Template.ExecuteTemplate" aria-label="Go to Template.ExecuteTemplate">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) ExecuteTemplate(wr <a href="/io">io</a>.<a href="/io#Writer">Writer</a>, name <a href="/builtin#string">string</a>, data <a href="/builtin#any">any</a>) <a href="/builtin#error">error</a></pre> </div> <p>ExecuteTemplate applies the template associated with t that has the given name to the specified data object and writes the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.Funcs" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go;l=174">Funcs</a> <a class="Documentation-idLink" href="#Template.Funcs" title="Go to Template.Funcs" aria-label="Go to Template.Funcs">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) Funcs(funcMap <a href="#FuncMap">FuncMap</a>) *<a href="#Template">Template</a></pre> </div> <p>Funcs adds the elements of the argument map to the template's function map. It must be called before the template is parsed. It panics if a value in the map is not a function with appropriate return type or if the name cannot be used syntactically as a function in a template. It is legal to overwrite elements of the map. The return value is the template, so calls can be chained. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.Lookup" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go;l=185">Lookup</a> <a class="Documentation-idLink" href="#Template.Lookup" title="Go to Template.Lookup" aria-label="Go to Template.Lookup">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) Lookup(name <a href="/builtin#string">string</a>) *<a href="#Template">Template</a></pre> </div> <p>Lookup returns the template with the given name that is associated with t. It returns nil if there is no such template or the template has no definition. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.Name" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go;l=48">Name</a> <a class="Documentation-idLink" href="#Template.Name" title="Go to Template.Name" aria-label="Go to Template.Name">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) Name() <a href="/builtin#string">string</a></pre> </div> <p>Name returns the name of the template. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.New" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go;l=59">New</a> <a class="Documentation-idLink" href="#Template.New" title="Go to Template.New" aria-label="Go to Template.New">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) New(name <a href="/builtin#string">string</a>) *<a href="#Template">Template</a></pre> </div> <p>New allocates a new, undefined template associated with the given one and with the same delimiters. The association, which is transitive, allows one template to invoke another with a {{template}} action. </p><p>Because associated templates share underlying data, template construction cannot be done safely in parallel. Once the templates are constructed, they can be executed in parallel. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.Option" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/option.go;l=42">Option</a> <a class="Documentation-idLink" href="#Template.Option" title="Go to Template.Option" aria-label="Go to Template.Option">露</a></span> <span class="Documentation-sinceVersion"> <span class="Documentation-sinceVersionLabel">added in</span> <span class="Documentation-sinceVersionVersion">go1.5</span> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) Option(opt ...<a href="/builtin#string">string</a>) *<a href="#Template">Template</a></pre> </div> <p>Option sets options for the template. Options are described by strings, either a simple string or "key=value". There can be at most one equals sign in an option string. If the option string is unrecognized or otherwise invalid, Option panics. </p><p>Known options: </p><p>missingkey: Control the behavior during execution if a map is indexed with a key that is not present in the map. </p><pre>"missingkey=default" or "missingkey=invalid" The default behavior: Do nothing and continue execution. If printed, the result of the index operation is the string "<no value>". "missingkey=zero" The operation returns the zero value for the map type's element. "missingkey=error" Execution stops immediately with an error. </pre> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.Parse" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go;l=204">Parse</a> <a class="Documentation-idLink" href="#Template.Parse" title="Go to Template.Parse" aria-label="Go to Template.Parse">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) Parse(text <a href="/builtin#string">string</a>) (*<a href="#Template">Template</a>, <a href="/builtin#error">error</a>)</pre> </div> <p>Parse parses text as a template body for t. Named template definitions ({{define ...}} or {{block ...}} statements) in text define additional templates associated with t and are removed from the definition of t itself. </p><p>Templates can be redefined in successive calls to Parse. A template definition with a body containing only white space and comments is considered empty and will not replace an existing template's body. This allows using Parse to add new named template definitions without overwriting the main template body. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.ParseFS" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/helper.go;l=146">ParseFS</a> <a class="Documentation-idLink" href="#Template.ParseFS" title="Go to Template.ParseFS" aria-label="Go to Template.ParseFS">露</a></span> <span class="Documentation-sinceVersion"> <span class="Documentation-sinceVersionLabel">added in</span> <span class="Documentation-sinceVersionVersion">go1.16</span> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) ParseFS(fsys <a href="/io/fs">fs</a>.<a href="/io/fs#FS">FS</a>, patterns ...<a href="/builtin#string">string</a>) (*<a href="#Template">Template</a>, <a href="/builtin#error">error</a>)</pre> </div> <p>ParseFS is like <a href="#Template.ParseFiles">Template.ParseFiles</a> or <a href="#Template.ParseGlob">Template.ParseGlob</a> but reads from the file system fsys instead of the host operating system's file system. It accepts a list of glob patterns (see <a href="/path#Match">path.Match</a>). (Note that most file names serve as glob patterns matching only themselves.) </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.ParseFiles" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/helper.go;l=55">ParseFiles</a> <a class="Documentation-idLink" href="#Template.ParseFiles" title="Go to Template.ParseFiles" aria-label="Go to Template.ParseFiles">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) ParseFiles(filenames ...<a href="/builtin#string">string</a>) (*<a href="#Template">Template</a>, <a href="/builtin#error">error</a>)</pre> </div> <p>ParseFiles parses the named files and associates the resulting templates with t. If an error occurs, parsing stops and the returned template is nil; otherwise it is t. There must be at least one file. Since the templates created by ParseFiles are named by the base (see <a href="/path/filepath#Base">filepath.Base</a>) names of the argument files, t should usually have the name of one of the (base) names of the files. If it does not, depending on t's contents before calling ParseFiles, t.Execute may fail. In that case use t.ExecuteTemplate to execute a valid template. </p><p>When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.ParseGlob" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/helper.go;l=117">ParseGlob</a> <a class="Documentation-idLink" href="#Template.ParseGlob" title="Go to Template.ParseGlob" aria-label="Go to Template.ParseGlob">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) ParseGlob(pattern <a href="/builtin#string">string</a>) (*<a href="#Template">Template</a>, <a href="/builtin#error">error</a>)</pre> </div> <p>ParseGlob parses the template definitions in the files identified by the pattern and associates the resulting templates with t. The files are matched according to the semantics of <a href="/path/filepath#Match">filepath.Match</a>, and the pattern must match at least one file. ParseGlob is equivalent to calling <a href="#Template.ParseFiles">Template.ParseFiles</a> with the list of files matched by the pattern. </p><p>When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. </p> </div><div class="Documentation-typeMethod"> <h4 tabindex="-1" id="Template.Templates" data-kind="method" class="Documentation-typeMethodHeader"> <span>func (*Template) <a class="Documentation-source" href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go;l=142">Templates</a> <a class="Documentation-idLink" href="#Template.Templates" title="Go to Template.Templates" aria-label="Go to Template.Templates">露</a></span> <span class="Documentation-sinceVersion"> </span> </h4> <div class="Documentation-declaration"> <pre>func (t *<a href="#Template">Template</a>) Templates() []*<a href="#Template">Template</a></pre> </div> <p>Templates returns a slice of defined templates associated with t. </p> </div> </div></section></div> </div> </div> <div class="UnitFiles js-unitFiles"> <h2 class="UnitFiles-title" id="section-sourcefiles"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/insert_drive_file_gm_grey_24dp.svg" alt=""> Source Files <a class="UnitFiles-idLink" href="#section-sourcefiles" title="Go to Source Files" aria-label="Go to Source Files">露</a> </h2> <div class="UnitFiles-titleLink"> <a href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template" target="_blank" rel="noopener">View all Source files</a> </div> <div> <ul class="UnitFiles-fileList"><li> <a href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/doc.go" target="_blank" rel="noopener" title="doc.go">doc.go</a> </li><li> <a href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/exec.go" target="_blank" rel="noopener" title="exec.go">exec.go</a> </li><li> <a href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/funcs.go" target="_blank" rel="noopener" title="funcs.go">funcs.go</a> </li><li> <a href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/helper.go" target="_blank" rel="noopener" title="helper.go">helper.go</a> </li><li> <a href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/option.go" target="_blank" rel="noopener" title="option.go">option.go</a> </li><li> <a href="https://cs.opensource.google/go/go/+/go1.24.0:src/text/template/template.go" target="_blank" rel="noopener" title="template.go">template.go</a> </li></ul> </div> </div> <div class="UnitDirectories js-unitDirectories"> <h2 class="UnitDirectories-title" id="section-directories"> <img class="go-Icon" height="24" width="24" src="/static/shared/icon/folder_gm_grey_24dp.svg" alt=""> Directories <a class="UnitDirectories-idLink" href="#section-directories" title="Go to Directories" aria-label="Go to Directories">露</a> </h2> <div class="UnitDirectories-toggles"> <div class="UnitDirectories-toggleButtons"> <button class="js-showInternalDirectories" data-test-id="internal-directories-toggle" data-gtmc="directories button" aria-label="Show Internal Directories"> Show internal </button> <button class="js-expandAllDirectories" data-test-id="directories-toggle" data-gtmc="directories button" aria-label="Expand All Directories"> Expand all </button> </div> </div> <table class="UnitDirectories-table UnitDirectories-table--tree js-expandableTable" data-test-id="UnitDirectories-table"> <tr class="UnitDirectories-tableHeader UnitDirectories-tableHeader--tree"> <th>Path</th> <th class="UnitDirectories-desktopSynopsis">Synopsis</th> </tr> <tr class=""> <td data-id="parse" data-aria-owns=""> <div class="UnitDirectories-pathCell"> <div><a href="/text/template/parse@go1.24.0">parse</a> </div> <div class="UnitDirectories-mobileSynopsis">Package parse builds parse trees for templates as defined by text/template and html/template.</div> </div> </td> <td class="UnitDirectories-desktopSynopsis">Package parse builds parse trees for templates as defined by text/template and html/template.</td></tr></tr> </table> </div> </div> </div> <div id="showInternal-description" hidden> Click to show internal directories. </div> <div id="hideInternal-description" hidden> Click to hide internal directories. </div> </article> <footer class="go-Main-footer"></footer> </main> <footer class="go-Footer"> <div class="go-Footer-links"> <div class="go-Footer-linkColumn"> <a href="https://go.dev/solutions" class="go-Footer-link go-Footer-link--primary" data-gtmc="footer link"> Why Go </a> <a href="https://go.dev/solutions#use-cases" class="go-Footer-link" data-gtmc="footer link"> Use Cases </a> <a href="https://go.dev/solutions#case-studies" class="go-Footer-link" data-gtmc="footer link"> Case Studies </a> </div> <div class="go-Footer-linkColumn"> <a href="https://learn.go.dev/" class="go-Footer-link go-Footer-link--primary" data-gtmc="footer link"> Get Started </a> <a href="https://play.golang.org" class="go-Footer-link" data-gtmc="footer link"> Playground </a> <a href="https://tour.golang.org" class="go-Footer-link" data-gtmc="footer link"> Tour </a> <a href="https://stackoverflow.com/questions/tagged/go?tab=Newest" class="go-Footer-link" data-gtmc="footer link"> Stack Overflow </a> <a href="https://go.dev/help" class="go-Footer-link" data-gtmc="footer link"> Help </a> </div> <div class="go-Footer-linkColumn"> <a href="https://pkg.go.dev" class="go-Footer-link go-Footer-link--primary" data-gtmc="footer link"> Packages </a> <a href="/std" class="go-Footer-link" data-gtmc="footer link"> Standard Library </a> <a href="/golang.org/x" class="go-Footer-link" data-gtmc="footer link"> Sub-repositories </a> <a href="https://pkg.go.dev/about" class="go-Footer-link" data-gtmc="footer link"> About Go Packages </a> </div> <div class="go-Footer-linkColumn"> <a href="https://go.dev/project" class="go-Footer-link go-Footer-link--primary" data-gtmc="footer link"> About </a> <a href="https://go.dev/dl/" class="go-Footer-link" data-gtmc="footer link">Download</a> <a href="https://go.dev/blog" class="go-Footer-link" data-gtmc="footer link">Blog</a> <a href="https://github.com/golang/go/issues" class="go-Footer-link" data-gtmc="footer link"> Issue Tracker </a> <a href="https://go.dev/doc/devel/release.html" class="go-Footer-link" data-gtmc="footer link"> Release Notes </a> <a href="https://blog.golang.org/go-brand" class="go-Footer-link" data-gtmc="footer link"> Brand Guidelines </a> <a href="https://go.dev/conduct" class="go-Footer-link" data-gtmc="footer link"> Code of Conduct </a> </div> <div class="go-Footer-linkColumn"> <a href="https://www.twitter.com/golang" class="go-Footer-link go-Footer-link--primary" data-gtmc="footer link"> Connect </a> <a href="https://www.twitter.com/golang" class="go-Footer-link" data-gtmc="footer link"> Twitter </a> <a href="https://github.com/golang" class="go-Footer-link" data-gtmc="footer link">GitHub</a> <a href="https://invite.slack.golangbridge.org/" class="go-Footer-link" data-gtmc="footer link"> Slack </a> <a href="https://reddit.com/r/golang" class="go-Footer-link" data-gtmc="footer link"> r/golang </a> <a href="https://www.meetup.com/pro/go" class="go-Footer-link" data-gtmc="footer link"> Meetup </a> <a href="https://golangweekly.com/" class="go-Footer-link" data-gtmc="footer link"> Golang Weekly </a> </div> </div> <div class="go-Footer-bottom"> <img class="go-Footer-gopher" width="1431" height="901" src="/static/shared/gopher/pilot-bust-1431x901.svg" alt="Gopher in flight goggles"> <ul class="go-Footer-listRow"> <li class="go-Footer-listItem"> <a href="https://go.dev/copyright" data-gtmc="footer link">Copyright</a> </li> <li class="go-Footer-listItem"> <a href="https://go.dev/tos" data-gtmc="footer link">Terms of Service</a> </li> <li class="go-Footer-listItem"> <a href="http://www.google.com/intl/en/policies/privacy/" data-gtmc="footer link" target="_blank" rel="noopener"> Privacy Policy </a> </li> <li class="go-Footer-listItem"> <a href="https://go.dev/s/pkgsite-feedback" target="_blank" rel="noopener" data-gtmc="footer link"> Report an Issue </a> </li> <li class="go-Footer-listItem"> <button class="go-Button go-Button--text go-Footer-toggleTheme js-toggleTheme" aria-label="Theme Toggle"> <img data-value="auto" class="go-Icon go-Icon--inverted" height="24" width="24" src="/static/shared/icon/brightness_6_gm_grey_24dp.svg" alt="System theme"> <img data-value="dark" class="go-Icon go-Icon--inverted" height="24" width="24" src="/static/shared/icon/brightness_2_gm_grey_24dp.svg" alt="Dark theme"> <img data-value="light" class="go-Icon go-Icon--inverted" height="24" width="24" src="/static/shared/icon/light_mode_gm_grey_24dp.svg" alt="Light theme"> <p> Theme Toggle </p> </button> </li> <li class="go-Footer-listItem"> <button class="go-Button go-Button--text go-Footer-keyboard js-openShortcuts" aria-label="Shorcuts Modal"> <img class="go-Icon go-Icon--inverted" height="24" width="24" src="/static/shared/icon/keyboard_grey_24dp.svg" alt=""> <p> Shortcuts Modal </p> </button> </li> </ul> <a class="go-Footer-googleLogo" href="https://google.com" target="_blank"rel="noopener" data-gtmc="footer link"> <img class="go-Footer-googleLogoImg" height="24" width="72" src="/static/shared/logo/google-white.svg" alt="Google logo"> </a> </div> </footer> <dialog id="jump-to-modal" class="JumpDialog go-Modal go-Modal--md js-modal"> <form method="dialog" data-gmtc="jump to form" aria-label="Jump to Identifier"> <div class="Dialog-title go-Modal-header"> <h2>Jump to</h2> <button class="go-Button go-Button--inline" type="button" data-modal-close data-gtmc="modal button" aria-label="Close" > <img class="go-Icon" height="24" width="24" src="/static/shared/icon/close_gm_grey_24dp.svg" alt="" /> </button> </div> <div class="JumpDialog-filter"> <input class="JumpDialog-input go-Input" autocomplete="off" type="text"> </div> <div class="JumpDialog-body go-Modal-body"> <div class="JumpDialog-list"></div> </div> <div class="go-Modal-actions"> <button class="go-Button" data-test-id="close-dialog">Close</button> </div> </form> </dialog> <dialog class="ShortcutsDialog go-Modal go-Modal--sm js-modal"> <form method="dialog"> <div class="go-Modal-header"> <h2>Keyboard shortcuts</h2> <button class="go-Button go-Button--inline" type="button" data-modal-close data-gtmc="modal button" aria-label="Close" > <img class="go-Icon" height="24" width="24" src="/static/shared/icon/close_gm_grey_24dp.svg" alt="" /> </button> </div> <div class="go-Modal-body"> <table> <tbody> <tr><td class="ShortcutsDialog-key"> <strong>?</strong></td><td> : This menu</td> </tr> <tr><td class="ShortcutsDialog-key"> <strong>/</strong></td><td> : Search site</td> </tr> <tr><td class="ShortcutsDialog-key"> <strong>f</strong> or <strong>F</strong></td><td> : Jump to</td> </tr> <tr> <td class="ShortcutsDialog-key"><strong>y</strong> or <strong>Y</strong></td> <td> : Canonical URL</td> </tr> </tbody> </table> </div> <div class="go-Modal-actions"> <button class="go-Button" data-test-id="close-dialog">Close</button> </div> </form> </dialog> <section class="Cookie-notice js-cookieNotice"> <div>go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic. <a target=_blank href="https://policies.google.com/technologies/cookies">Learn more.</a></div> <div><button class="go-Button">Okay</button></div> </section> <script> // this will throw if the querySelector can鈥檛 find the element const gtmId = document.querySelector('.js-gtmID').dataset.gtmid; if (!gtmId) { throw new Error('Google Tag Manager ID not found'); } loadScript(`https://www.googletagmanager.com/gtm.js?id=${gtmId}`); </script> <noscript> <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-W8MVQXG" height="0" width="0" style="display:none;visibility:hidden"> </iframe> </noscript> <div class="js-canonicalURLPath" data-canonical-url-path="/text/template@go1.24.0" hidden></div> <div class="js-playgroundVars" data-modulepath="std" data-version="v1.24.0" hidden></div> <script> loadScript('/static/frontend/unit/main/main.js') </script> <script> loadScript('/static/frontend/unit/unit.js') </script> </body> </html>