github.com/jacobsoderblom/buffalo@v0.11.0/render/js.go (about)

     1  package render
     2  
     3  import (
     4  	"html/template"
     5  	"strings"
     6  
     7  	"github.com/gobuffalo/plush"
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  // JavaScript renders the named files using the 'application/javascript'
    12  // content type and the github.com/gobuffalo/plush
    13  // package for templating. If more than 1 file is provided
    14  // the second file will be considered a "layout" file
    15  // and the first file will be the "content" file which will
    16  // be placed into the "layout" using "<%= yield %>".
    17  func JavaScript(names ...string) Renderer {
    18  	e := New(Options{})
    19  	return e.JavaScript(names...)
    20  }
    21  
    22  // JavaScript renders the named files using the 'application/javascript'
    23  // content type and the github.com/gobuffalo/plush
    24  // package for templating. If more than 1 file is provided
    25  // the second file will be considered a "layout" file
    26  // and the first file will be the "content" file which will
    27  // be placed into the "layout" using "<%= yield %>". If no
    28  // second file is provided and an `JavaScriptLayout` is specified
    29  // in the options, then that layout file will be used
    30  // automatically.
    31  func (e *Engine) JavaScript(names ...string) Renderer {
    32  	if e.JavaScriptLayout != "" && len(names) == 1 {
    33  		names = append(names, e.JavaScriptLayout)
    34  	}
    35  	hr := templateRenderer{
    36  		Engine:      e,
    37  		contentType: "application/javascript",
    38  		names:       names,
    39  	}
    40  	return hr
    41  }
    42  
    43  // JSTemplateEngine renders files with a `.js` extension through Plush.
    44  // It also implements a new `partial` helper that will run non-JS partials
    45  // through `JSEscapeString` before injecting.
    46  func JSTemplateEngine(input string, data map[string]interface{}, helpers map[string]interface{}) (string, error) {
    47  	var pf partFunc
    48  	var ok bool
    49  	if pf, ok = helpers["partial"].(func(string, Data) (template.HTML, error)); !ok {
    50  		return "", errors.New("could not find a partial function")
    51  	}
    52  
    53  	helpers["partial"] = func(name string, dd Data) (template.HTML, error) {
    54  		if strings.Contains(name, ".js") {
    55  			return pf(name, dd)
    56  		}
    57  		h, err := pf(name, dd)
    58  		if err != nil {
    59  			return "", errors.WithStack(err)
    60  		}
    61  		he := template.JSEscapeString(string(h))
    62  		return template.HTML(he), nil
    63  	}
    64  
    65  	return plush.BuffaloRenderer(input, data, helpers)
    66  }
    67  
    68  type partFunc func(string, Data) (template.HTML, error)