Go in Practice, Second Edition cover
welcome to this free extract from
an online version of the Manning book.
to read more
or

9 HTML and email template patterns

 

This chapter covers

  • Adding functionality inside templates
  • Nesting templates
  • Using template inheritance
  • Rendering objects to HTML
  • Using email templates

When you’re programmatically creating text or HTML responses in many programming environments, you need to seek out the right library to handle producing the HTML to return. In previous chapters, we’ve often output formatted strings directly to a writer. But in the real world, this is hard to maintain, leads to a lot of work, and is more prone to error. It’s trivial to introduce cross-site scripting (XSS) problems, for example, by not accounting for user input properly. In most languages, developers would reach for a third-party templating library. Go handles this a little differently. In the standard library, Go provides template handling for both text and HTML. The HTML handling, including security for untrusted data, is built on top of the text template engine to add HTML-aware intelligence.

Although the standard library enables you to work with HTML templates, it stops short of being overly opinionated. Instead, it provides a foundation along with the ability to extend and combine templates. You could nest templates or have a template inherit from another one, for example. This simple and extensible design allows you to use many common template patterns.

9.1 Working with HTML templates

9.1.1 Standard library HTML package overview

9.1.2 Adding functionality inside templates

9.1.3 Limiting template parsing

9.1.4 When template execution breaks

9.1.5 Mixing templates

9.2 Using templates for email

Summary