mustache / spec

The Mustache spec.
MIT License
365 stars 71 forks source link

Mustache shouldn't alter whitespace inside partials #2

Closed bobthecow closed 13 years ago

bobthecow commented 13 years ago

Whitespace is sacred in HTML.

Mustache (per the current spec) plays fast and loose with whitespace inside partials.

This causes unexpected results:

template.mustache

<body>
    <div>
        {{> body }}
    </div>
</body>

body.mustache

<p>
    <textarea>{{ text_with_newlines }}</textarea>
</p>

context.yml

text_with_newlines: |
    This is a
    newline test

output

<body>
    <div>
        <p>
            <textarea>This is a
        newline test</textarea>
        </p>
    </div>
</body>

This is no-me-gusta. I think the "Indentation should be prepended to each line of the partial" portion of the spec should be dropped completely.

See also: this issue on Mustache.php.

ghost commented 11 years ago

Tache solves this by using template objects (which can optionally be precompiled):

view = {
  "task-input-result" => Tache::Template.new("\/\/ Return inputs as task result\n\tprintf(\"%s\\n\", taskInput1);\nprintf(\"%s\\n\", taskInput2);\n"),
  "task-input-variables" => Tache::Template.new("\/\/ Task input variables \nchar *taskInput1 = argv[1];\nchar *taskInput2 = argv[2];\n")
}
Tache.render(template, view)

Indents will then work as expected as per https://github.com/groue/GRMustache/issues/45 and only newlines are needed in the values. This is due to the concept of a 'line' token in my parser, which also allows for precompiled templates to work in the same way.

I will add more documentation to Tache for this but in the meantime see (specifically the multiline example):

groue commented 11 years ago

Thanks for the feedback, @thelucid! This is a very interesting approach indeed, to turn data into a dynamic partial, and use the spec-defined indentation. Quite smart indeed. And another validation of our approach of dynamic partials :-)

ghost commented 11 years ago

@groue No problem. If it helps, take a look at my parser tests to see under what circumstances the 'line' tokens appear: https://github.com/thelucid/tache/blob/master/test/parser_test.rb ...and how they are used here: https://github.com/thelucid/tache/blob/master/lib/tache/template.rb

groue commented 11 years ago

Thanks @thelucid.

groue commented 11 years ago

For those interested, here is another white-space processing use case not covered by the specification: https://github.com/groue/GRMustache/issues/46.

The user wants to have

{{ statement-1 }}
{{ statement-2 }}
{{ statement-3 }}

Render as:

1
3

For the following data:

{ "statement-1": "1",
  "statement-3": "3" }

Notice how the template line containing {{ statement-2 }} has not been rendered.