Giter VIP home page Giter VIP logo

mustache's People

Contributors

abh avatar ags799 avatar amarshall avatar benjaminparnell avatar cbroglie avatar chbug avatar danielwhite avatar ddliu avatar frohmut avatar fuktommy avatar gsempe avatar hoisie avatar iwamot avatar jmadler avatar jornh avatar jsoizo avatar kei10in avatar kishaningithub avatar kpumuk avatar reddec avatar roblillack avatar samwhited avatar sporkmonger avatar themihai avatar vieiralucas avatar xakep666 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

mustache's Issues

AllowMissingVariables = false should report missing variables at any depth.

given the following template

You have {{count}} items:
{{#sections}}
--{{name}}--
{{#items}}
{{.}}
{{/items}}
{{/sections}}

If I do the following:

    mustache.AllowMissingVariables = false
    s, err := mustache.Render(tmpl, map[string]interface{}{
        //"count": 2,
        "sections": map[string]interface{}{
            "name":  "Stuff",
            "items": []string{"foo", "bar"},
        },
    })
    fmt.Println(s, err)

I receive Missing variable "count"

Like I expect. The same goes for sections. But, if I give it the following:

    mustache.AllowMissingVariables = false
    s, err := mustache.Render(tmpl, map[string]interface{}{
        "count": 2,
        "sections": map[string]interface{}{
            //"name": "Stuff",
            "items": []string{"foo", "bar"},
        },
    })
    fmt.Println(s, err)

I get:

You have 2 items:
----
foo
bar

I would expect something along the lines of Missing variable "sections.name" or, at the very least Missing variable "name".

I feel like, if you're going to have a global variable called "AllowMissingVariables", it should apply at every level or, at the very least, the limits of its scope should be clearly noted in the docs.

Remove `golangci-lint` from `go.mod`

Dear developers,

If i understand correctly, you can always run golangci-lint from command line (or GitHub Actions), but no need to include it as a dependent package in go.mod. Is it possible to remove it from go.mod and make the dependent packages minimalist? :)

I generated a relationship map of dependent packages for gofiber/template which involves mustache as a supported html template engine, it's quite interesting:

gofiber/template#117

Inconsistent behaviour with name conflicts

I had some confusing results that turned out to be related to a naming conflict. The code below illustrates the behaviour I encountered. Obviously, I can work around this by renaming or hiding a variable, now that I've realised that it is connected to a name conflict. This wasn't obvious in my application code.

main.go:

package main

import (
	"fmt"

	"github.com/cbroglie/mustache"
)

type Doc struct {
	Content []Value
}

func (d Doc) Values() []Value {
	return d.Content
}

type Value struct {
	Content interface{}
}

func (v Value) IsLink() bool {
	_, ok := v.Content.(Link)
	return ok
}

type Link struct {
	URL  string
	Text string
}

func main() {
	output, err := mustache.RenderFile(
		"test.mustache",
		Doc{
			Content: []Value{
				{Content: Link{URL: "https://golang.org", Text: "Burrow 01"}},
			},
		},
	)

	if err != nil {
		panic(err)
	}

	fmt.Print(output)
}

test.mustache:

{{#Values}}

{{#IsLink}}
Have checked that this is a link
    <a href="{{Content.URL}}">{{Content.Text}}</a>
Content = {{Content}}
{{/IsLink}}

Have NOT checked that this is a link
    <a href="{{Content.URL}}">{{Content.Text}}</a>
Content = {{Content}}

{{/Values}}

output:

Have checked that this is a link
    <a href=""></a>
Content = [{{https://golang.org Burrow 01}}]

Have NOT checked that this is a link
    <a href="https://golang.org">Burrow 01</a>
Content = {https://golang.org Burrow 01}

dot-notation for nested data..method output map -> map key?

Hey cbroglie, thanks for taking over maintenance of this great lib, it seems that your and @jabley's forks are the two most developed since @hosie's went quiet.

I'm just developing something using the original hosie code, and I've noticed it doesn't appear to do nested queries using dot-notation. I think @Wuvist added this feature in his fork, I'm wondering whether you could pull from his, and I could switch to using your repo?

It's a pity something that got so many fans and forks got abandoned, there are lots of forks pushing some great features but not enough cohesion. :(

Change delimiter

The readme mentions that there is support for changing the delimiter, but this doesn't seem to be the case.

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? Is there some other way to get same results?

List variable names present in a template

As a user I would like to be able to extract the variable names that are present in the template.
One of the main reasons is that it would make it a lot easier to get those variables in a programatic way.
If you have a DB or file or API that provides the variables, and you have 200 or them in total, but only 4 present in a template, it would make it a lot faster and secure to get only the 4 you need.

For example:

This is a variable called {{ var_name }}, please allow a way of listing it.

File (Template) Variables list:
["var_name"]

Publish binaries of the CLI tool

Now that we have a CLI version, we should publish release builds through github so users can leverage the tool w/o installing Go.

Capital letters in struct field names

Lets assume we have such struct:
type Products struct {
Gtin string json:"gtin,omitempty"
Name Lang json:"name,omitempty"
}

From somwhere i recieve such template:
{{gtin}} blah {{name}}

And now, because I have no impact on this template and my structure fields MUST be public (golang to make it public use capital letters in names) I have inconsistency gtin<->Gtin.
As a result only "blah" will be shown.
Is it possible to add some "ignore capitalisation" switch?
Otherwise I have to make some initial parsing which seems to be usless effort (and has impact on performance).

Lambda

Was wondering if Lambda should be recognized as a language in Visual Studio Code (version 1.20.0), 2018 because Lambda is an 'expression', and there exist 4 types of linguistic expressions, which Lambda falls into the 4th category of "performing actions". Lambda is used in the construction of expression; it is also used as an argument(s).

By UMN.EDU standards, expressions are notable languages. The reason I bring this to your attention is that in Visual Studio Code, in my command palette, preferences: configure language specific settings and in the drop down menu, Lambda isn't listed as a language specific setting; even though it is an expression, and expressions are deemed specific form(s) of language, and which also means, I can't select Lambda when configuring my .NET applications, unless the configurations are provided elsewhere for such a task.

The reason for this pull request review is to make a determination as to whether Lambda should officially be considered a language, and thereby listed in my preferences for language specific settings.

Respectfully,
YRM64
"The Purple Rose"

Updated steps for installing CLI

Looks like the 'go get github.com/cbroglie/mustache/...' is deprecated now. Could you help me by providing the updated command to install the cli wrapper?

Error: unknow flag: --layout

Hi,

I'm trying to run the command below:

mustache sosrecarga.json templates/sosrecarga/home.mustache --layout templates/sosrecarga/layout.mustache

And he returns this error to me:

Error: unknow flag: --layout

valueInd.IsZero undefined on recent update

Here is the error stack:
/cbroglie/mustache/mustache.go:549:18: valueInd.IsZero undefined (type reflect.Value has no field or method IsZero)
It worked before, but broken only recently.

Replacement in partial removes a newline

Test:

func TestMustacheRenderPartials(t *testing.T) {
	expected := "header\n\n\tline 1\n\tline 2\n\nfooter\n"

	staticProvider := &mustache.StaticProvider{
		Partials: map[string]string{
			"body": strings.Join([]string{
				"\tline 1",
				"\tline 2",
			}, "\n"),
		},
	}

	actual, err := mustache.RenderPartials(
		"header\n\n{{> body}}\n\nfooter\n",
		staticProvider,
		map[string]string{},
	)

	assert.NoError(t, err)
	assert.Equal(t, expected, actual)
}

I'm expecting there to be two newlines after replacing {{> body}} in the template but there's only one newline after that replacement.

Print JSON data structures as a value using CLI

Hi, and thanks for maintaining this great project! I am trying to find a way to present random JSON data structures in an HTML file that is rendered using the mustache CLI.

Given the following example:

["a", "b"]

...I'd like to see the following ]results:

["a", "b"]

...but get:

[a b]

in the resulting document. Any ideas on how to achieve this goal? Thanks!

Binary/CLI?

I'm looking to install mustache just as a binary, but the default in the Ubuntu package manager is the CLI tool provided by the ruby implementation. Well then I need all this Ruby junk just to run a template engine! Go and it's static binary output seems perfect for the task. Any interest in creating a CLI on top of your library that would match the Ruby implementation?

Thanks!
-Seth

Policy on Reporting Potential Security Vulnerabilities

Hello,

I wanted to inquire about any existing policy/your preference for reporting any potential security vulnerability findings. Rather than just opening a public issue, I wanted to check whether there was a responsible disclosure policy of some kind, and/or a private channel through which findings can be reported. Thanks!

Support for identifying the last item in a collection or hanging commas?

I would be using this to generate JSON which causes problems with hanging commas. For example:

Template:

{
   "user_name": {{email}}
   "update_ids": {
   {{#items}}
      {{item.id}},
   {{/items}}
}

Input JSON:

{
  "email": "[email protected]",
  "items": [
    {
      "item": {
        "id": 123,
        "name": "Something"
      }
    },
    {
      "item": {
        "id": 456,
        "name": "Who cares"
      }
    }
  ]
}

Output JSON:

{
   "user_name":"[email protected]",
   "update_ids":[
      123,
      456,     <--------------- hanging comma
   ]
}

As you can see the output JSON will be invalid since there is a hanging comma at the end. There are a few work arounds like updating the objects in items to include a last boolean value etc. but i'm curious if there is any sort of built in support with your library that would allow us to handle this more elegantly.

Miss render on `&` char (golang)

I am trying to render an URL using Render function on mustache (golang). When I try to render this http://example.com?param1=1&param2=2 the result is http://example.com?param1=1&amp;param2=2

The template I use is like this:

map[string]string{
   "URL":"http://example.com?param1=1&param2=2",
}

The text I want to render is like this:
I want to access this url={{URL}}

Am I not using the function correctly? Thanks inadvance

How do you set new delimiters?

The documentation says that changing delimiters is a supported feature, but I am not seeing how to set new delimiters?

Is there a method for this? The Template type is all un-exported so one cannot create a template and set the tags that way either.

Context stacks seem to be walked the wrong direction for bool sections

Hi @cbroglie πŸ‘‹

variable name resolution in bool sections that are inside list sections seems to be broken: variables are resolved in the outer context first, before checking the inner one.

Let's take a look at this minimal example that can be added to the testcases in mustache_test.go and will make it fail immediately:

{`{{#section}}{{#bool}}{{x}}{{/bool}}{{/section}}`,
map[string]interface{}{
	"x": "broken",
	"section": []map[string]interface{}{
		{"x": "working", "bool": true},
	},
}, "working", nil},

So, the code is:

  1. happily iterating section section -> cool πŸ‘
  2. diving into the bool section because that's true -> cool πŸ‘
  3. trying to resolve x, but starts at the bottom of the stack (ie. the outer context) and finds β€œbroken” there -> not cool. 😭

Command-line binary?

Is there any chance that there would be a standalone binary that could be used from command line?

I'm envisioning something like this:

mustache data.yaml template.mustache > result.txt

I wouldn't imagine HTML escaping would be enabled, but maybe that would be controlled by an option passed to the program.

Would such a thing be difficult? Does this already exist?

go get fails

$ go get github.com/cbroglie/mustache
# cd /Users/themihai/go/src/github.com/cbroglie/mustache; git submodule update --init --recursive
No submodule mapping found in .gitmodules for path 'spec'
package github.com/cbroglie/mustache: exit status 1

Error: line 5: interleaved closing tag: each

I'm trying to loop through the properties of an object. According to stackoverflow this should be supported, but I get the error:

Error: line 5: interleaved closing tag: each

This is my template

{{#each .}}
    Key: {{@key}} Value = {{this}}
{{/each}}

And my data looks like this:

{
  "base-image": {
    "type": "unknown"
  },
  "nixosConfigurations": {
    "ahorn": {
      "type": "nixos-configuration"
    },
    "birne": {
      "type": "nixos-configuration"
    },
    "bob": {
      "type": "nixos-configuration"
    },
    "kartoffel": {
      "type": "nixos-configuration"
    },
    "kfbox": {
      "type": "nixos-configuration"
    },
    "porree": {
      "type": "nixos-configuration"
    }
  },
  "nixosModules": {
    "activation-secrets": {
      "type": "nixos-module"
    },
  }
}

Selector for index in an array: items.0.name

In other implementations of mustache there is the ability to write a selector into an array by the index. Ex: items.0.name. This doesn't seem possible with the golang implementation. I understand how it is potentially free in JS, but it would require extra effort in golang. Is this something that could be supported in the future?

Similar requests by other libraries (with mixed results):
Python: defunkt/pystache#196
C#: DanieleScipioni/Mustache#2
Erlang: soranoba/bbmustache#41
Swift: groue/GRMustache.swift#2

Alternative idea: Methods that support params.
golang's text/template supports index lookup with functions.

{{ (index .items 0).Name }}

try it: https://play.golang.org/p/dgIMARysMOX

It looks like this library already supports functions on the struct, but it didn't seem to support params. If it did, then a getter could be added as needed.

valueInd.IsZero undefined

github.com\cbroglie\mustache\mustache.go:549:18: valueInd.IsZero undefined (type reflect.Value has no field or method IsZero)

go version 1.12.6

Access parent element in loop with same name as child element

Given the following YAML:

---
name: cashew
data: hello
projects:
  - name: mustache
  - name: pystache

And the following Mustache:

Parent Name: {{name}}
{{data}}
{{#projects}}
    Top Child Data: {{data}}
    Parent Name: {{#.}}{{name}}{{/.}}
    Child Name: {{name}}
{{/projects}}

I am getting the following output:

Parent Name: cashew
hello
    Top Child Data: hello
    Parent Name: mustache
    Child Name: mustache
    Top Child Data: hello
    Parent Name: pystache
    Child Name: pystache

How can I access the top level object element from within the loop with the same name as a child's element?

Feature request: Metadata methods for Template type

I suggest that we add *Template methods that return useful metadata about the rendered template, e.g.

func (*Template) GetVariables() []string {
    // return array of variables
}

func (*Template) GetSections() []strings

which could loop over the elems array of the Template that was produced by parse() and extract the unique list of variables and sections. Similarly, getTags() could return some sort of nested structure of sections with their variables.

What do you think?

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.