GithubHelp home page GithubHelp logo

mustache's Introduction

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/template. mustache.go is fast -- it parses templates efficiently and stores them in a tree-like structure which allows for fast execution.

Documentation

For more information about mustache, check out the mustache project page or the mustache manual.

Also check out some example mustache files

Installation

To install mustache.go, simply run go get github.com/hoisie/mustache. To use it in a program, use import "github.com/hoisie/mustache"

Usage

There are four main methods in this package:

func Render(data string, context ...interface{}) string

func RenderFile(filename string, context ...interface{}) string

func ParseString(data string) (*Template, os.Error)

func ParseFile(filename string) (*Template, os.Error)

There are also two additional methods for using layouts (explained below).

The Render method takes a string and a data source, which is generally a map or struct, and returns the output string. If the template file contains an error, the return value is a description of the error. There's a similar method, RenderFile, which takes a filename as an argument and uses that for the template contents.

data := mustache.Render("hello {{c}}", map[string]string{"c":"world"})
println(data)

If you're planning to render the same template multiple times, you do it efficiently by compiling the template first:

tmpl,_ := mustache.ParseString("hello {{c}}")
var buf bytes.Buffer;
for i := 0; i < 10; i++ {
    tmpl.Render (map[string]string { "c":"world"}, &buf)  
}

For more example usage, please see mustache_test.go

Escaping

mustache.go follows the official mustache HTML escaping rules. That is, if you enclose a variable with two curly brackets, {{var}}, the contents are HTML-escaped. For instance, strings like 5 > 2 are converted to 5 &gt; 2. To use raw characters, use three curly brackets {{{var}}}.

Layouts

It is a common pattern to include a template file as a "wrapper" for other templates. The wrapper may include a header and a footer, for instance. Mustache.go supports this pattern with the following two methods:

func RenderInLayout(data string, layout string, context ...interface{}) string

func RenderFileInLayout(filename string, layoutFile string, context ...interface{}) string

The layout file must have a variable called {{content}}. For example, given the following files:

layout.html.mustache:

<html>
<head><title>Hi</title></head>
<body>
{{{content}}}
</body>
</html>

template.html.mustache:

<h1> Hello World! </h1>

A call to RenderFileInLayout("template.html.mustache", "layout.html.mustache", nil) will produce:

<html>
<head><title>Hi</title></head>
<body>
<h1> Hello World! </h1>
</body>
</html>

A note about method receivers

Mustache.go supports calling methods on objects, but you have to be aware of Go's limitations. For example, lets's say you have the following type:

type Person struct {
    FirstName string
    LastName string    
}

func (p *Person) Name1() string {
    return p.FirstName + " " + p.LastName
}

func (p Person) Name2() string {
    return p.FirstName + " " + p.LastName
}

While they appear to be identical methods, Name1 has a pointer receiver, and Name2 has a value receiver. Objects of type Person(non-pointer) can only access Name2, while objects of type *Person(person) can access both. This is by design in the Go language.

So if you write the following:

mustache.Render("{{Name1}}", Person{"John", "Smith"})

It'll be blank. You either have to use &Person{"John", "Smith"}, or call Name2

Supported features

  • Variables
  • Comments
  • Change delimiter
  • Sections (boolean, enumerable, and inverted)
  • Partials

mustache's People

Contributors

abh avatar benjaminparnell avatar chbug avatar ddliu avatar gagliardetto avatar hoisie avatar kpumuk avatar samwhited avatar sporkmonger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mustache's Issues

Is this project still under maintained?

Here is my fork:
https://github.com/Wuvist/mustache

What I have done so far:

No support for {{.}} notation.

Mustache uses {{.}} to access the top of the context stack. This is important primarily for arrays or slices of strings.

assigning "compiled" templates to a global variable

if you "compile" a template (with ParseFile), its type is *mustache.template, that is not visible outside the package. I'd like to assign it to a (global) variable to complile once and use it everywhere in my program. So why not make it of a *mustache.Template type? I've tried a brutal name substitution in the mustache.go file, and it seems to work (sorry, I'm fairly new to both go and mustache.go). THX

Interface change suggestion

This would mean that a literal template and a layout file (or vice versa) could be mixed in the same call. What do you think? If I implemented this would you merge it? The original API would still work.

In client code:

// Order of arguments is irrelevant
output := mustache.Render(
        mustache.Literal( "Here's my data: {{myData}}" ),
        mustache.LayoutFilename("./defaultlayout.mustache"),
        map[string]string{"myData":"Yes, this is my data"} )

In mustache.go:

type dataType int

const (
    uninitialisedDataType dataType = iota
    templateLiteral
    templateFilename
    layoutLiteral
    layoutFilename
)

type templateDescription struct {
    dataType
    data string
}

func Render(args ...interface{}) string {
    // If the first argument is a string then behave as original API
    // If using new API then only use the first occurrences of template and layout
    // ...
}

func Literal(template string) templateDescription {
    return templateDescription{templateLiteral, template}
}

func Filename(filename string) templateDescription {
    return templateDescription{templateFilename, filename}
}

func LayoutLiteral(template string) templateDescription {
    return templateDescription{layoutLiteral, template}
}

func LayoutFilename(filename string) templateDescription {
    return templateDescription{layoutFilename, filename}
}

Is it possible to iterate over a slice?

I was attempting to iterate over users ([]user), and output attributes on the struct. However, it doesn't seem to do anything once it hits {#users}. I checked the _tests on the project and the only example of this in the test appears to be commented out?

Support for recursive partials

Mustache supposedly allows for recursive partials, which are useful for rendering nested/heirarchical data like trees and lists etc.

I think this might be somewhat hard to accomplish due to the fact we compile/parse the template before we render it, so partials are evaluated even if they're wrapped in sections which are empty.

Is there some way around this? Any planned support?

Update examples from unexported *template return type

In this section:
"

There are four main methods in this package:

func Render(data string, context ...interface{}) string

func RenderFile(filename string, context ...interface{}) string

func ParseString(data string) (*template, os.Error)

func ParseFile(filename string) (*template, os.Error)
"

Some of the return types are *template, not *Template as they should be

Go panics on some malformed templates

I tried creating a template with {{}} in an {{#enumerated_section}} and mustache.go threw a string bounds panic (full dump below). I see a number of explicit panic() calls in mustache.go so maybe this is not undesired behavior.

PC=0x14b7f index 0<0>0
throw: string bounds

panic PC=0x8a6ec0
throw+0x3e /Users/peter/Code/go/src/pkg/runtime/runtime.c:74
throw(0xe11d8, 0x0)
prbounds+0x92 /Users/peter/Code/go/src/pkg/runtime/string.c:108
prbounds(0xe11f8, 0x0, 0x0, 0x0, 0x0, ...)
runtime.indexstring+0x82 /Users/peter/Code/go/src/pkg/runtime/string.c:214
runtime.indexstring(0x7c71a, 0x0, 0x0, 0x0, 0x0, ...)
mustache.*template·parseSection+0x368 /Users/peter/Code/mustache.go/mustache.go:145
mustache.*template·parseSection(0x127e640, 0x0, 0x9613a0, 0x0, 0x7c6d1, ...)
mustache.*template·parse+0x439 /Users/peter/Code/mustache.go/mustache.go:192
mustache.*template·parse(0x127e640, 0x0, 0x12750f0, 0x0)
mustache.ParseString+0xc2 /Users/peter/Code/mustache.go/mustache.go:316
mustache.ParseString(0x7c548, 0x0, 0x296, 0x0, 0xb0e78, ...)
mustache.Render+0x25 /Users/peter/Code/mustache.go/mustache.go:345
mustache.Render(0x7c548, 0x0, 0x296, 0x0, 0xb0e78, ...)

panicln no longer exists in latest release of Go

mustache.go can be updated:

  $ git diff
  diff --git a/mustache.go b/mustache.go
  index 146099a..18b5f7c 100644
  --- a/mustache.go
  +++ b/mustache.go
  @@ -156,7 +156,7 @@ func (tmpl *template) parseSection(section *sectionElement) os.Error {
               tmpl.elems.Push(partial)
           case '=':
               if tag[len(tag)-1] != '=' {
  -                panicln("Invalid meta tag")
  +                panic("Invalid meta tag")
               }
               tag = strings.TrimSpace(tag[1 : len(tag)-1])
               newtags := strings.Split(tag, " ", 0)
  @@ -227,7 +227,7 @@ func (tmpl *template) parse() os.Error {
               tmpl.elems.Push(partial)
           case '=':
               if tag[len(tag)-1] != '=' {
  -                panicln("Invalid meta tag")
  +                panic("Invalid meta tag")
               }
               tag = strings.TrimSpace(tag[1 : len(tag)-1])
               newtags := strings.Split(tag, " ", 0)

Custom path of partials

ParseString used the current working directory for handling of partials.
Would be interesting to define custom path of partials.
Has sometimes may need to set different paths depending on various situations

Thank you very much.
Tosh.

crash in mustache.go

{{#a}}
{{#b}}
{{/a}}
{{/b}}

These are nested wrong. However, this should produce an error, not a crash (nil pointer dereference).

Need template examples up front.

In the main readme, it would be great if I could see a Hello World template in the Mustache language, as supported by this lib.

Thanks.

output writer

I hope that mustache.go take an argument for output writer.
Maybe, it will be helpful for web.go

web.Get("/", func(ctx *web.Context) {
  data := GetData()
  tmpl.RenderFile("foobar.mustache", data, ctx)
})

Supply parameters for functions

In go mustache templates one of the examples showed how to retrieve Name1 function value into mustache template. But Name1 didn't have any parameters. Can I somehow use functions that have to receive parameters? (according to mustache documentation, lambdas is a way out, but I don't see any activity regarding #16 or #25). Is there some other way to get same results?

Render and RenderFile no longer return errors

This is bizarre because it must be intentional... which did you change Render and RenderFile to only return a string?

This goes against normal Go convention, which is when an Error is possible, have a return of (Whatever, os.Error), that way we can check to see if err != nil and handle errors that way.

Please fix this! You are a GREAT asset to the go community and it would be sad if one of Go's best programmers changed convention, because if you do, others probably will too :(

Lambda sections are not executed

According to the mustache manual, when using a function/method as the value of a section it should be called when rendering the template.
There are functions related to this in the code, but they are not called and I can't figure out what I'd have to change to get this to work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.