Feel free to clone and explore the code, or to follow along with the tutorial to create the application from scratch. You can find the code for this tutorial on GitHub. To follow along with the tutorial, you need to have Go installed and set up on your system. A complete overview of templates can be found here. You can also define your own functions and use them in the template. The above outputs Hello James! to the console.Īpart from accessing data, you can use actions like if to conditionally render content, and range to iterate over a collection. T, err := template.New("test").Parse(tmpl) To render the template, you must parse the template with the Parse function and use the Execute function, which takes a writer and the data object as arguments and writes the output to the writer. Name accesses the Name field of the object. character in the action refers to the data object passed to the template, and. The above template has a single action that prints the value of the Name field of the data object passed to the template. Here’s an example template: tmpl := "Hello !" The actions are used to access or evaluate data, or to control the template’s structure. This makes html/template a better choice for generating HTML output, and is why this article will use the html/template package.Ī template is simply a string with some special commands called actions, which are enclosed in double curly braces. Both offer the exact same set of interfaces the only difference is that the latter automatically secures the HTML output against various attacks. In Go, there are two packages that provide the templating functionality: the text/template and html/template packages. A very popular real-life use of a Go template is in the kubectl command line tool, where you can pass a template to the -template flag to customize the output to your needs. Templates are often used to generate web pages, emails, and other text-based outputs. You can customize how the data is displayed by passing an object to a template. Go templates are a robust feature used to generate text or HTML outputs based on data in a Go program. Mathematics postgraduate who has a passion for computers and software.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |