A strongly typed HTML templating language that compiles to Go code, and has great developer tooling.

Overview

templ

  • A strongly typed HTML templating language that compiles to Go code, and has great developer tooling.

vscode-autocomplete

Getting started

  • Install the templ command-line tool: go install github.com/a-h/templ/cmd/[email protected]
  • Create a *.templ file containing a template.
  • Run templ generate to create Go code from the template.

Current state

This is beta software, and the template language may still have breaking changes. There's no guarantees of stability or correctness at the moment.

If you're keen to see Go be practical for Web projects, see "Help needed" for where the project needs your help.

Features

The language generates Go code, some sections of the template (e.g. package, import, if, for and switch statements) are output directly as Go expressions in the generated output, while HTML elements are converted to Go code that renders their output.

  • templ generate generates Go code from *.templ files.
  • templ fmt formats template files in the current directory tree.
  • templ lsp provides a Language Server to support IDE integrations. The compile command generates a sourcemap which maps from the *.templ files to the compiled Go file. This enables the templ LSP to use the Go language gopls language server as is, providing a thin shim to do the source remapping. This is used to provide autocomplete for template variables and functions.

Security

templ currently uses context unaware escaping, see https://github.com/a-h/templ/issues/6 for a proposal to add context-aware content escaping.

Design

Overview

  • *.templ files are used to generate Go code to efficiently render the template at runtime.
  • Go code is generated from template files using the templ generate command, while templates can be formatted with the templ fmt command. The templ lsp command provides an LSP (Language Server Protocol) server to enable autocomplete.
  • Each {% templ ComponentName(params Params) %} section compiles into a function that creates a templ.Component.
  • templ.Component is an interface with a single function - Render(ctx context.Context, io.Writer) (err error). You can make a component entirely in Go code and interact with it via templ.
  • templ aims for correctness, simplicity, developer experience and raw performance, in that order. The goal is to make writing Go web applications more practical, achievable and desirable.
  • Provides minified HTML output only.
  • Components can be composed into layouts.

Package

Since templ files are as close to Go as possible, they start with a package expression.

{% package templ %}

Importing packages

After the package expression, they might import other Go packages, just like Go files. There's no multi-line import statement, just a single import per line.

{% import "strings" %}

Components

Once the package and import statements are done, we can define components using the {% templ Name(params Params) %} expression. The templ expressions are converted into Go functions when the templ generate command is executed.

{% templ AddressView(addr Address) %}
	
{%= addr.Address1 %}
{%= addr.Address2 %}
{%= addr.Address3 %}
{%= addr.Address4 %}
{% endtempl %}

Each templ.Component can contain HTML elements, strings, for loops, switch statements and references to other templates.

Referencing other components

Components can be referenced in the body of the template, and can pass data between then, for example, using the AddressTemplate from the PersonTemplate.

{% templ PersonTemplate(p Person) %}
	
{% for _, v := range p.Addresses %} {%! AddressTemplate(v) %} {% endfor %}
{% endtempl %}

It's also possible to create "higher order components" that compose other instances of templ.Component without passing data, or even knowing what the concrete type of the component will be ahead of time. So long as is implements templ.Component, it can be used.

For example, this template accepts 3 templates (header, footer, body) and renders all 3 of them in the expected order.

{% templ Layout(header, footer, body templ.Component) %}
	{%! header %}
	{%! body %}
	{%! footer %}
{% endtempl %}

Code-only components

It's possible to create a templ.Component entirely in Go code. Within templ, strings are automatically escaped to reduce the risk of cross-site-scripting attacks, but it's possible to create your own "Raw" component that bypasses this behaviour:

func Raw(s string) templ.Component {
	return templ.ComponentFunc(func(ctx context.Context, w io.Writer) (err error) {
		_, err = io.WriteString(w, s)
		return
	})
}

Then call it in a template. So long as the Raw function is in scope, you can use it.

alert('xss vector');") %} ">
{%! Raw("") %}

Elements

HTML elements look like HTML and you can write static attributes into them, just like with normal HTML. Don't worry about the spacing, the HTML will be minified when it's rendered.

{%= addr.Address1 %}
">
{%= addr.Address1 %}

You can also have dynamic attributes that use template parameter, other Go variables that happen to be in scope, or call Go functions that return a string. Don't worry about HTML encoding element text and attribute values, that will be taken care of automatically.

Text

Text is rendered from Go expressions, which includes constant values:

{%= "this is a string" %}

Using the backtick format (single-line only):

{%= `this is also a string` %}

Calling a function that returns a string:

{%= time.Now().String() %}

Or using a string parameter, or variable that's in scope.

{%= v.s %}

What you can't do, is write text directly between elements (e.g.

Some text
, because the parser would have to become more complex to support HTML entities and the various mistakes people make when they're doing that (bare ampersands etc.). Go strings support UTF-8 which is much easier, and the escaping rules are well known by Go programmers.

If/Else

Templates can contain if/else statements that follow the same pattern as Go.

{%= "Test user" %} {% else %} {%= "Not test user" %} {% endif %} ">
{% if p.Type == "test" %}
	{%= "Test user" %}
{% else %}
	{%= "Not test user" %}
{% endif %}

For

Templates have the same loop behaviour as Go.

{% for _, v := range p.Addresses %}
	
  • {%= v.City %}
  • {% endfor %}

    Switch/Case

    Switch statements work in the same way as they do in Go.

    {%= "Test user" %} {% endcase %} {% case "admin" %} {%= "Admin user" %} {% endcase %} {% default %} {%= "Unknown user" %} {% enddefault %} {% endswitch %} ">
    {% switch p.Type %}
    	{% case "test" %}
    		{%= "Test user" %}
    	{% endcase %}
    	{% case "admin" %}
    		{%= "Admin user" %}
    	{% endcase %}
    	{% default %}
    		{%= "Unknown user" %}
    	{% enddefault %}
    {% endswitch %}
    

    Full example

    {%= addr.Address1 %}
    {%= addr.Address2 %}
    {%= addr.Address3 %}
    {%= addr.Address4 %}
    {% endtempl %} {% templ PersonTemplate(p Person) %}
    {%= p.Name() %}
    {%= strings.ToUpper(p.Name()) %}
    {% if p.Type == "test" %} {%= "Test user" %} {% else %} {%= "Not test user" %} {% endif %} {% for _, v := range p.Addresses %} {%! AddressTemplate(v) %} {% endfor %} {% switch p.Type %} {% case "test" %} {%= "Test user" %} {% endcase %} {% case "admin" %} {%= "Admin user" %} {% endcase %} {% default %} {%= "Unknown user" %} {% enddefault %} {% endswitch %}
    {% endtempl %} ">
    {% package templ %}
    
    {% import "strings" %}
    
    {% templ Layout(header, footer, body templ.Component) %}
    	{%! header %}
    	{%! body %}
    	{%! footer %}
    {% endtempl %}
    
    {% templ AddressTemplate(addr Address) %}
    	
    {%= addr.Address1 %}
    {%= addr.Address2 %}
    {%= addr.Address3 %}
    {%= addr.Address4 %}
    {% endtempl %} {% templ PersonTemplate(p Person) %}
    {%= p.Name() %}
    {%= strings.ToUpper(p.Name()) %}
    {% if p.Type == "test" %} {%= "Test user" %} {% else %} {%= "Not test user" %} {% endif %} {% for _, v := range p.Addresses %} {%! AddressTemplate(v) %} {% endfor %} {% switch p.Type %} {% case "test" %} {%= "Test user" %} {% endcase %} {% case "admin" %} {%= "Admin user" %} {% endcase %} {% default %} {%= "Unknown user" %} {% enddefault %} {% endswitch %}
    {% endtempl %}

    Will compile to Go code similar to the following (error handling removed for brevity):

    ") _, err = io.WriteString(w, templ.EscapeString(addr.Address1)) _, err = io.WriteString(w, "
    ") _, err = io.WriteString(w, "
    ") _, err = io.WriteString(w, templ.EscapeString(addr.Address2)) _, err = io.WriteString(w, "
    ") // Cut for brevity. return err }) } func PersonTemplate(p Person) (t templ.Component) { return templ.ComponentFunc(func(ctx context.Context, w io.Writer) (err error) { _, err = io.WriteString(w, "
    ") _, err = io.WriteString(w, "
    ") _, err = io.WriteString(w, templ.EscapeString(p.Name())) _, err = io.WriteString(w, "
    ") _, err = io.WriteString(w, "") _, err = io.WriteString(w, templ.EscapeString(strings.ToUpper(p.Name()))) _, err = io.WriteString(w, "") _, err = io.WriteString(w, "
    ") if p.Type == "test" { _, err = io.WriteString(w, "") _, err = io.WriteString(w, templ.EscapeString("Test user")) _, err = io.WriteString(w, "") } else { _, err = io.WriteString(w, "") _, err = io.WriteString(w, templ.EscapeString("Not test user")) _, err = io.WriteString(w, "") } for _, v := range p.Addresses { err = AddressTemplate(v).Render(ctx, w) } switch p.Type { case "test": _, err = io.WriteString(w, "") _, err = io.WriteString(w, templ.EscapeString("Test user")) _, err = io.WriteString(w, "") case "admin": _, err = io.WriteString(w, "") _, err = io.WriteString(w, templ.EscapeString("Admin user")) _, err = io.WriteString(w, "") default: _, err = io.WriteString(w, "") _, err = io.WriteString(w, templ.EscapeString("Unknown user")) _, err = io.WriteString(w, "") } _, err = io.WriteString(w, "
    ") _, err = io.WriteString(w, "
    ") return err }) } ">
    // Code generated by templ DO NOT EDIT.
    
    package templ
    
    import "github.com/a-h/templ"
    import "context"
    import "io"
    import "strings"
    
    func Layout(header, footer, body templ.Component) (t templ.Component) {
    	return templ.ComponentFunc(func(ctx context.Context, w io.Writer) (err error) {
    		err = header.Render(ctx, w)
    		err = body.Render(ctx, w)
    		err = footer.Render(ctx, w)
    		return err
    	})
    }
    
    func AddressTemplate(addr Address) (t templ.Component) {
    	return templ.ComponentFunc(func(ctx context.Context, w io.Writer) (err error) {
    		_, err = io.WriteString(w, "
    ") _, err = io.WriteString(w, templ.EscapeString(addr.Address1)) _, err = io.WriteString(w, "
    "
    ) _, err = io.WriteString(w, "
    ") _, err = io.WriteString(w, templ.EscapeString(addr.Address2)) _, err = io.WriteString(w, "
    "
    ) // Cut for brevity. return err }) } func PersonTemplate(p Person) (t templ.Component) { return templ.ComponentFunc(func(ctx context.Context, w io.Writer) (err error) { _, err = io.WriteString(w, "
    ") _, err = io.WriteString(w, "
    ") _, err = io.WriteString(w, templ.EscapeString(p.Name())) _, err = io.WriteString(w, "
    "
    ) _, err = io.WriteString(w, ") _, err = io.WriteString(w, " href=") _, err = io.WriteString(w, "\"") _, err = io.WriteString(w, templ.EscapeString(p.URL)) _, err = io.WriteString(w, "\"") _, err = io.WriteString(w, ">") _, err = io.WriteString(w, templ.EscapeString(strings.ToUpper(p.Name()))) _, err = io.WriteString(w, "") _, err = io.WriteString(w, "
    ") if p.Type == "test" { _, err = io.WriteString(w, "") _, err = io.WriteString(w, templ.EscapeString("Test user")) _, err = io.WriteString(w, "") } else { _, err = io.WriteString(w, "") _, err = io.WriteString(w, templ.EscapeString("Not test user")) _, err = io.WriteString(w, "") } for _, v := range p.Addresses { err = AddressTemplate(v).Render(ctx, w) } switch p.Type { case "test": _, err = io.WriteString(w, "") _, err = io.WriteString(w, templ.EscapeString("Test user")) _, err = io.WriteString(w, "") case "admin": _, err = io.WriteString(w, "") _, err = io.WriteString(w, templ.EscapeString("Admin user")) _, err = io.WriteString(w, "") default: _, err = io.WriteString(w, "") _, err = io.WriteString(w, templ.EscapeString("Unknown user")) _, err = io.WriteString(w, "") } _, err = io.WriteString(w, "
    "
    ) _, err = io.WriteString(w, "
    "
    ) return err }) }

    IDE Support

    vim / neovim

    A vim / neovim plugin is available from https://github.com/Joe-Davidson1802/templ.vim which adds syntax highlighting.

    Neovim 5 supports Language Servers directly. For the moment, I'm using https://github.com/neoclide/coc.nvim to test the language server after using Joe-Davidson1802's plugin to set the language type:

    {
      "languageserver": {
        "templ": {
          "command": "templ",
          "args": ["lsp"],
          "filetypes": ["templ"]
        }
    }

    To add extensive debug information, you can include additional args to the LSP, like this:

    {
      "languageserver": {
        "templ": {
          "command": "templ",
          "args": ["lsp",
            "--log", "/Users/adrian/github.com/a-h/templ/cmd/templ/lspcmd/templ-log.txt", 
    	"--goplsLog", "/Users/adrian/github.com/a-h/templ/cmd/templ/lspcmd/gopls-log.txt",
    	"--goplsRPCTrace", "true"
          ],
          "filetypes": ["templ"]
        }
    }

    vscode

    There's a VS Code extension, just make sure you've already installed templ and that it's on your path.

    Development

    Local builds

    To build a local version you can use the go build tool:

    cd cmd/templ
    go build
    

    Testing

    Unit tests use the go test tool:

    go test ./...
    

    Release testing

    This project uses https://github.com/goreleaser/goreleaser to build the command line binary and deploy it to Github. You will need to install this to test releases.

    make build-snapshot
    

    The binaries are created by me and signed by my GPG key. You can verify with my key https://adrianhesketh.com/a-h.gpg

    Inspiration

    Doesn't this look like a lot like https://github.com/valyala/quicktemplate ?

    Yes, yes it does. I looked at the landscape of Go templating languages before I started writing code and my initial plan was to improve the IDE support of quicktemplate, see https://github.com/valyala/quicktemplate/issues/80

    The package author didn't respond (hey, we're all busy), and looking through the code, I realised that it would be hard to modify what's there to have the concept of source mapping, mostly because there's no internal object model of the language, it reads and emits code in one go.

    It's also a really feature rich project, with all sorts of formatters, and support for various languages (JSON etc.), so I borrowed some syntax ideas, but left the code. If valyala is up for it, I'd be happy to help integrate the ideas from here. I just want Go to have a templating language with great IDE support.

    Hot reload

    For hot reload, you can use https://github.com/cosmtrek/air

    For documentation on how to use it with templ see https://adrianhesketh.com/2021/05/28/templ-hot-reload-with-air/

    Help needed

    The project is looking for help with:

    • Adding features to the Language Server implementation, it just does autocomplete and error reporting the moment. It needs to be able to do definition and add imports automatically.
    • Examples and testing of the tools.
    • Writing a blog post that demonstrates using the tool to build a form-based Web application.
    • Testing (including fuzzing), benchmarking and optimisation.
    • An example of a web-based UI component library would be very useful, a more advanced version of the integration test suite, thatwould be a Go web server that runs the compiled templ file along with example JSON payloads that match the expected data structure types and renders the content - a UI playground. If it could do hot-reload, amazing.
    • Low priority, but I'm thinking of developing a CSS-in-Go implementation to work in parallel. This might take the form of a pre-processor which would collect all "style" attributes of elements and automatically calculate a minimum set of CSS classes that could be created and applied to the elements - but a first pass could just be a way to define CSS classes in Go to allow the use of CSS variables.

    Please get in touch if you're interested in building a feature as I don't want people to spend time on something that's already being worked on, or ends up being a waste of their time because it can't be integrated.

    Issues
    • Improve install process

      Improve install process

      Hello,

      I'm trying to install templ, and I have a couple of suggestions to make it easier to install:

      Include an "Install" section in README.md

      I might have missed a section, but I didn't see how to install templ from the README, only how to build locally. It can be a really short section, but also really helpful :) If you'd like inspiration, I'm pretty happy with how my Install section turned out.

      Make templ easily go installable

      I was able to install templ with go install github.com/a-h/templ/cmd, but because the last directory is named cmd, the binary is now named cmd on my system. If you moved it to github.com/a-h/templ/cmd/templ, I would be able to run go install github.com/a-h/templ/cmd/templ and end up with a binary named templ

      Use GoReleaser's HomeBrew support

      GoReleaser can support generating Homebrew formulas so MacOS users can do something like brew install a-h/tap/templ if they wish. They won't even need GOPATH/bin in their PATH, because Homebrew will manage paths. I use this functionality for a little CLI I wrote and it works well once you get the tap repo and access token build- very much set up and forget. Feel free to take inspiration from my .goreleaser.yml

      opened by bbkane 5
    • DOCTYPE declaration causes strangeness in the vscode extension

      DOCTYPE declaration causes strangeness in the vscode extension

      When creating a .templ file I noticed a very strange thing happening if the layout had a doctype declaration.

      For example, this code (which looks like it should be valid to me):

      {% package templates %}
      
      {% templ Layout(content templ.Component) %}
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Document</title>
      </head>
      <body>
          {%! content %}
      </body>
      </html>
      {% endtempl %}
      
      {% templ Layout1(content templ.Component) %}
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Document</title>
      </head>
      <body>
          {%! content %}
      </body>
      </html>
      {% endtempl %}
      
      

      when this was saved in vscode, immediately turns into:

      {% package templates %}
      

      i.e. the actual templ declarations were removed.

      The actual layout was much more detailed but I distilled it down to the fact that if any templ declaration with a doctype declaration exists in the templ file then all templ declarations are removed, but only if the first templ declaration is the one that contains the doctype. Having the templ declarations the other way round (Layout1 first, followed by Layout) it works fine.

      I hope it's just me.

      Any ideas?

      opened by pharrisee 4
    • Feature request: LSP publish template syntax errors

      Feature request: LSP publish template syntax errors

      When template parsing fails, the error messages should be published to the client to inform the user in the IDE where issues are as per https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_publishDiagnostics

      enhancement good first issue 
      opened by a-h 2
    • Cannot parse empty attribute

      Cannot parse empty attribute

      nav.templ:

          1 {% package templates %}
          2 
          3 {% import "container/types" %}
          4 
          5 {% templ NavTemplate(apps []types.AppConfig) %}
          6     <nav data-turbo-permanent>       
          7         <h1>{%= "Go Feed Me" %}</h1>
          8         <ul>
          9             {% for _, a := range apps %}
         10                 <li>
         11                     <a href={%= a.Url %}  data-turbo-frame="container">{%= a.Name %}</a>
         12                 </li>
         13             {% endfor %}
         14         </ul>
         15     </nav>
         16 {% endtempl %}
      

      nav_templ.go (it stops after the imports):

      >>  1 // Code generated by templ DO NOT EDIT.
          2 
          3 package templates
          4 
      >>  5 import "github.com/a-h/templ"
      >>  6 import "context"
      >>  7 import "io"
      >>  8 import "container/types"
      

      Strangely enough this also fails when I try 'data-turbo-permanent="true"' potentially todo with the dashes aswell?

      Tried doing a "valueless" attribute without dashes like "hidden". That also resulted in the same outut.

      opened by Joe-Davidson1802 2
    • Feature request - VS Code plugin

      Feature request - VS Code plugin

      It looks fairly straightforward to create a VS Code plugin for templ, as per the getting started guide at: https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide

      I think it is possible to make the outline of the templ tags ({% import ... %} etc.) and then refer to HTML and Go syntax blocks to reduce the overall amount of work required.

      The templ lsp command provides a language server that will take care of other elements.

      enhancement help wanted good first issue 
      opened by a-h 1
    • Feature request: boolean attributes

      Feature request: boolean attributes

      HTML supports boolean attributes, see https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes

      <hr noshade/>
      

      For true boolean attribute values, the spec states that <hr noshade="noshade"/> can be used.

      However, the attribute name must be omitted for false values. <hr noshade=""/> is actually a true value. This makes it impossible for templ to dynamically omit a boolean attribute, because the current design only supports string expressions.

      This causes problems for implementing Turbo support because flags such as the boolean attributes disabled and autoscroll are required to be altered based on template parameters.

      To resolve this, I propose adding:

      • Support for constant boolean attributes: <hr noshade/> as per HTML.
      • Support for boolean expression attributes: <hr noshade={%= templ.Bool(true) %}/>

      Note that the boolean expression attribute value starts with templ.Bool. This would be used in the parser to ensure that the generated code expects a boolean expression at compile time. If this marker wasn't present, then attribute expressions would have to return any type (interface{}) and the generated code would have to check at runtime whether the value was a string or boolean.

      One of the goals of templ is to blow up at compile time, not runtime. Supporting an expression that returned anything (e.g. int64, time.Time, big.Rat) would mean checking types at runtime. I don't want to get templ to decide which date format is used on behalf of the developer displaying a date.

      opened by a-h 1
    • Support self-closing tags

      Support self-closing tags

      Currently attempting to use self closing tags throws an error in some cases.

      Case 1:

      In this case since the input is the last in the parent element generator seems to allow it and writes a </input> after.

      <div>
          <input type="text" name="title" id="title" placeholder="Todo..." />
      </div>
      

      Case 2:

      In this case as self closing tags exist as children that aren't at the end of the parent an error is thrown: parsing error: <meta>: mismatched end tag, expected '</meta>', got '</link>'

      <head>
          <title>{%= "Hotwire Todo - " + title %}</title>
          <meta charset="utf-8" />
          <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/out/water.min.css" />
          <script type="module">{%! Raw("import hotwiredTurbo from 'https://cdn.skypack.dev/@hotwired/turbo';") %}</script>
      </head>
      
      opened by Joe-Davidson1802 1
    • Let goreleaser manage versioning via ldflags

      Let goreleaser manage versioning via ldflags

      I noticed running templ version prints devel even when using a release downloaded from github releases.

      Since goreleaser sets main.version via ldflags this should ensure it's picked up. I think it's possible to use ReadBuildInfo with goreleaser but requires some additional config.

      I tested this using the dry run feature of goreleaser which seemed to work.

      make build-snapshot
      ./dist/templ_darwin_amd64/templ version
      v0.0.98-next
      
      opened by steinfletcher 1
    • <br> tag handling


      tag handling

      From the reference

      A br element must have a start tag but must not have an end tag. https://www.w3.org/TR/2011/WD-html-markup-20110113/br.html#br-tags

      In templ br is treated as a void tag as per the above tech reference. Adding <br> in the templ file fails to compile. <br/> compiles OK but this is rendered as <br></br> which chrome interprets as a double <br> tag, e.g. <br><br> which creates a double line break.

      opened by steinfletcher 0
    • Feature request: Introduce context-aware escaping

      Feature request: Introduce context-aware escaping

      templ currently uses simple escaping rules, described below:

      {% templ Example() %}
      <script type="text/javascript">
        {%= "will be escaped using templ.Escape, which isn't JavaScript-aware" %}
      </script>
      <div onClick={%= "will be escaped using templ.Escape, which isn't JavaScript aware" %}>
        {%= "will be escaped using templ.Escape, which is fine" %}</div>  
      </div>
      <style type="text/css">
        {%= "will be escaped using templ.Escape, which isn't CSS-aware" %}
      </style>
      <div style={%= "will be escaped using templ.Escape, which isn't CSS-aware" %}</div>
      <div>{%= "will be escaped using templ.Escape, which is fine" %}</div>
      <a href={%= "will be escaped using templ.Escape, which isn't hyperlink-aware" %}</div>
      {% endtempl %}
      

      This approach is safe when the content being applied to the onClick / on* / style, attributes and script / style element contents are from trusted sources, but if not, they could become attack vectors.

      In most cases, developers won't be adding hyperlinks, or populating onClick elements from user-controlled content, but since it's a potential attack vector, it's probably worth making developers explicitly state the safety, despite the extra developer hassle.

      templ's element type should be aware of href, on* and style attributes and the contents of script and style tags, and automatically apply context-aware escaping improve the security posture of templ.

      In cases where developers need to use content (css, scripts, hyperlinks) from data that's under their control (i.e. not potentially under an attacker's control), they'll need to state that the content is "safe".

      Language changes

      Option 1 - New string expression operator

      This could be done by adding a new context unaware string expression operator that only uses the templ.Escape function, rather than context-aware escaping. The syntax could be:

      • {%!=
      • {%= safe

      Option 2 - Force a function call to safehtml

      Make the CSS, onClick etc. take appropriate types from https://github.com/google/safehtml and force users to use safehtml.StyleFromConstant method calls.

      I think this would be irritating, because it's such a long function call.

      Option 3 - Wrap the function call to safehtml

      Similar, to above, but create a github.com/a-h/templ/safe package and shorten the calls:

      • {%= safe.Style("background-color: red") %}
      • {%= safe.Script("alert('hello')") %}

      Decision

      I don't like adding new templ expressions unless really required, so while I like option 1 (particularly the {%!= operator), I think option 3 is the way to go, because it's very clear what's going on even if you've never seen templ before, and there's not many places where developers will actually need to do this (onClick handlers, contents of <script> tags, style attributes).

      While it's potentially a breaking change for some users, we're not stable, so I think it's a good change.

      opened by a-h 2
    • LSP: Enable automatic insertion of HTML close tags

      LSP: Enable automatic insertion of HTML close tags

      As per https://github.com/microsoft/language-server-protocol/issues/715

      It looks like it's possible to intercept edits, and then use the https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit feature initiated from the server to insert the end tag, just like the XML example in the issue.

      I'm currently working on doing this for the templ language elements, so there will be something to base this on.

      enhancement good first issue 
      opened by a-h 1
    Releases(v0.0.126)
    Owner
    Adrian Hesketh
    Adrian Hesketh
    Amber is an elegant templating engine for Go Programming Language, inspired from HAML and Jade

    amber Notice While Amber is perfectly fine and stable to use, I've been working on a direct Pug.js port for Go. It is somewhat hacky at the moment but

    Ekin Koc 879 Aug 23, 2021
    The powerful template system that Go needs

    Plush Plush is the templating system that Go both needs and deserves. Powerful, flexible, and extendable, Plush is there to make writing your template

    Buffalo - The Go Web Eco-System 655 Sep 7, 2021
    A sweet velvety templating package

    Velvet Velvet is a templating package for Go. It bears a striking resemblance to "handlebars" based templates, there are a few small changes/tweaks, t

    Buffalo - The Go Web Eco-System 71 Aug 15, 2021
    Handlebars for golang

    raymond Handlebars for golang with the same features as handlebars.js 3.0. The full API documentation is available here: http://godoc.org/github.com/a

    Aymerick 440 Aug 27, 2021
    A template to build dynamic web apps quickly using Go, html/template and javascript

    gomodest-template A modest template to build dynamic web apps in Go, HTML and sprinkles and spots of javascript. Why ? Build dynamic websites using th

    Adnaan Badr 54 Aug 28, 2021
    An ERB-style templating language for Go.

    Ego Ego is an ERb style templating language for Go. It works by transpiling templates into pure Go and including them at compile time. These templates

    Ben Johnson 504 Sep 13, 2021
    pongo2 is a Django-syntax like templating-language

    Django-syntax like template-engine for Go

    Florian Schlachter 2k Sep 14, 2021
    Templating system for HTML and other text documents - go implementation

    FAQ What is Kasia.go? Kasia.go is a Go implementation of the Kasia templating system. Kasia is primarily designed for HTML, but you can use it for any

    Michał Derkacz 72 May 4, 2021
    Package damsel provides html outlining via css-selectors and common template functionality.

    Damsel Markup language featuring html outlining via css-selectors, extensible via pkg html/template and others. Library This package expects to exist

    Daniel Skinner 24 Sep 12, 2020
    A handy, fast and powerful go template engine.

    Hero Hero is a handy, fast and powerful go template engine, which pre-compiles the html templates to go code. It has been used in production environme

    Lime 1.5k Sep 10, 2021
    Programatic document generation as a HTTP service. Render PDFs using LaTeX templates and JSON.

    LaTTe Generate PDFs using LaTeX templates and JSON. Try out the demo! Find LaTTe on Docker Hub Table of Contents About Obtaining LaTTe Running & Using

    Raphael Reyna 164 Aug 25, 2021
    Razor view engine for go

    gorazor gorazor is the Go port of the razor view engine originated from asp.net in 2011. In summary, gorazor is: Extremely Fast. Templates are convert

    null 787 Sep 13, 2021
    Fast, powerful, yet easy to use template engine for Go. Optimized for speed, zero memory allocations in hot paths. Up to 20x faster than html/template

    quicktemplate A fast, powerful, yet easy to use template engine for Go. Inspired by the Mako templates philosophy. Features Extremely fast. Templates

    Aliaksandr Valialkin 2.2k Sep 12, 2021
    comparing the performance of different template engines

    goTemplateBenchmark comparing the performance of different template engines full featured template engines Ace Amber Go Handlebars removed - Kasia Mus

    null 189 Aug 31, 2021
    Simple system for writing HTML/XML as Go code. Better-performing replacement for html/template and text/template

    Simple system for writing HTML as Go code. Use normal Go conditionals, loops and functions. Benefit from typing and code analysis. Better performance than templating. Tiny and dependency-free.

    Nelo Mitranim 3 Sep 8, 2021
    gtpl is a template engine for glang

    gtpl 使用必读 gtpl is a HTML template engine for golang gtpl 是一个 go 语言模板引擎,它能以极快的速度进行模板语法分析。相比 go 语言官方库 html/template,gtpl 的语法有着简练、灵活、易用的特点。

    null 4 Jul 27, 2021
    The mustache template language in Go

    Overview mustache.go is an implementation of the mustache template language in Go. It is better suited for website templates than Go's native pkg/temp

    Michael Hoisie 1k Aug 27, 2021
    The world’s most powerful template engine and Go embeddable interpreter.

    The world’s most powerful template engine and Go embeddable interpreter

    Open2b 17 Sep 15, 2021
    HTML template engine for Go

    Ace - HTML template engine for Go Overview Ace is an HTML template engine for Go. This is inspired by Slim and Jade. This is a refinement of Gold. Exa

    Keiji Yoshida 803 Sep 10, 2021