janl / mustache.js Goto Github PK
View Code? Open in Web Editor NEWMinimal templating with {{mustaches}} in JavaScript
Home Page: https://mustache.github.io
License: MIT License
Minimal templating with {{mustaches}} in JavaScript
Home Page: https://mustache.github.io
License: MIT License
pls see:
http://gist.github.com/295977
-dpree
The build philosophy and specifically the Rakefile need some love. Not being judgmental but these are some questions I have and would like to fix if they are simply bugs:
lib/mustache.js
is "kept in sync" with mustache.js
however the opposite has happened.commonjs
target does not build the same way as all the others (with the pre and post templates)commonjs
target does not actually build a CommonJS module.I believe I have solved points 2-4 in my master branch: http://github.com/jhs/mustache.js. I tightened up the Rakefile and use the existing templating framework to expose Mustache
's parts.
For now, I left lib/
alone however it looks very much like code rot.
I will not pass judgment but just assume there are legacy requirements.
If a partial is ""
this throws an error:
if(!partials || !partials[name]) {
throw({message: "unknown_partial '" + name + "'"});
}
I know it's unusual to have an empty template, but it still seems like unexpected behavior.
I can't seem to get a nested array to return anything.
see the following commit for an example (uses the github commit api):
http://github.com/bitzesty/hud/commit/1fcd2a08e39664810d141e410c2b2269d4cd0e35#L1R40
Be honest: did you run the test suite before committing? :p
The fix for #26 is too aggressive. When rendering a partial, it wipes out the in-progress buffer. Please see and/or pull a candidate fix at http://github.com/jhs/mustache.js/tree/fix_partial. Thanks!
The escape function will re-escape the & in HTML Entities. Maybe this is working as intended.
Ex
This
&
Becomes this
&
Adds the hat (^), so you can create sections which are rendered if the key's value is false or an empty list.
http://github.com/defunkt/mustache.js/compare/inverted_sections
I have a string in my template which contains some {{strings}}. But I don't want them to be escaped.
Apparently there's no way to escape the strings so they don't get parsed by mustache.
What'd be cool would that we could do :
\{\{string\}\}
Which wouldn't be escaped as it's escaped.
The Mustache manual at http://mustache.github.com/mustache.5.html says that comment tags like {{! this }}
are stripped out. But they are not in mustache.js.
The test case for comments has the incorrect expected output. Please see http://github.com/jhs/mustache.js/commit/d82a1174d768c0de6e8e70e75a3366f2866b7fc4 for the fix. Thanks!
According to http://mustache.github.com/mustache.5.html , the ampersand character can also be used to unescape a variable. mustache.js does not follow the spec in this regard.
Below is a patch that treats '{{&' the same as '{{{':
http://github.com/thegrandpoobah/mustache.js/commit/a83dd64573e254cf775a58f72d17d9459e2b318a
Basically, if you have partial references inside a section, Mustache will fall into the "render_tags" function twice for the same template fragment. The first time is obviously necessary, but the second time seems unneeded to me. Usually this isn't an issue since the fragment has already been parsed and {{}}'s replaced.
But if you use the Delimiters feature, the delimiters get stripped on the first run, which makes the second run also do some parsing. This either leads to exceptions being thrown, or over-parsing of a template.
For example:
Base:
{{#enumerate}}
{{>partial}}
{{/enumerate}}
Partial:
{{=[[ ]]=}}
{{#text}}
[[={{ }}=]}
View:
{ enumerate: [ { text: 'A' }, { text: 'B' } ] }
will result in the following output:
A
B
whereas I think it should result in the following output:
{{text}}
{{text}}
Am I misinterpreting how Mustache should be working under this scenario?
Anyways, I've committed this test case to my fork:
http://github.com/thegrandpoobah/mustache.js/commit/5f07924fd998f3528b82530eae156739285c205a
I'm having problems with a template where I use Mustache to set the attribute value and it's containing a ".
In the escpae method i see this:
case '"': return '\"';
which should maybe be:
case '"': return '\\"';
But that doesn't work in this case:
$.mustache('<must ache="oo{{attr}}oo">Ook!</must>', { attr: '"' })
// => "<must ache="oooo">Ook!</must>"
Both cases just remove it since it needs to be htmlified.
This works:
case '"': return """
// => "<must ache="oo"oo">Ook!</must>"
I know they were originally in mustache.js, but I think they should be added back and made part of the spec.
Let's suppose the following :
var content = "Hello World";
var mustache = Mustache.to_html(content, {});
There's nothing dynamic in the content (yeah then, mustache isn't useful. But it could happen).
I get the content once, if returns :
Hello World
I call the Mustache.to_html
method again, it returns :
Hello World
Hello World
Every time we call again the method, it returns the content with all the ones called before.
When trying to use doc object in a show function from CouchDB
http://friendpaste.com/5SHrIIqZKam47I89H4J1mE
the following template :
http://friendpaste.com/1y54EjOayW18hYumRNOJyO
doesn't display doc.title and doc.content. I just get the html without values. But if instead of passing { doc: doc), I use { title: doc.title, content: doc.content } everything is ok.
Is this expected behavior? What is wrong in my template on the first case ?
Am I missing something? I run this command:
rake spec
...
All the specs failed.
Try the following JS code:
var a = Mustache.to_html('{{tag1}}\n\n\n{{tag2}}.\n', {tag1:'Hello', tag2:'World'}, {});
a should contain the string
Hello\n\n\nWorld.\n
whereas currently it contains the string
Hello\nWorld.
The problem stems from the default send function tossing away empty strings.
Not the biggest issue considering whitespace isn't the most important thing in HTML, but it would be nice if Mustache preserved newlines.
merge: function(a, b) {
var _new = {};
If a or b are clones of another prototype, their proto's properties are lost
The test case for issue 44 exposes this bug as well.
The problem is that the delimiter character is escaped for use in regular expressions, but includes uses a straight string search, not the regex variants. So it is searching for the '' character when it shouldn't be.
A potential fix is located at: http://github.com/thegrandpoobah/mustache.js/commit/27ea4e546869be2f5fe3e98d1064ab4d578f8639
Please note that my fork parses an extended Mustache syntax, so be careful if you are planning merging the change back to master.
here's the patch plus speedup bonus since toString() is slow anyways
return (s + '').replace(/&(?!\w+;)|["<>]/g, function(s) {.....
jashkenas said 1 day ago:
Hey janl.
Would you consider adding something like the following to Mustache?
(Or even better, something with the same API that actually pre-compiles the template string).
Best wishes,
-- Jeremy Ashkenas
janl said 1 day ago:
Hi Jeremy,
this looks interesting, but what problem does it solve? :)
Cheers
Jan
jashkenas said 1 day ago:
Hey Jan.
I guess that there are two reasons for it -- the technical reason and the real reason.
The technical reason is for potentially faster template evaluations (especially in a loop). A hypothetical Mustache.template() function that takes in a template string but no data could perform as much pre-compilation as possible. Looking at the current source, it could at least run render_pragmas() only once, instead of repeatedly for every evaluation of the template.
The real reason is to make the calling convention standard with other JavaScript templating libraries, in particular, with Protoype and Underscore.js. At DocumentCloud, we're about to open-source a Rails asset packager that has built-in support for managing JavaScript templates (JST). In the configuration file, you can specify a template function, like "_.template" (Underscore), or "new Template" (Prototype). All templates in the asset package are run through the template function and made available to your code in the browser. It's certainly possible to turn the template function off and just send down the raw strings, but it's much nicer to have the templates ready-to-go.
Taking a quick look around, it seems like the jQuery Template Plugin and ExtJS templates also follow this pattern. So I guess there's a third reason, the interoperability reason, where we can imagine a sort of JST standard, where all JavaScript template libraries provide a function that can be used to compile a template, returning a function or object that, when called with data, produces the output.
-- Jeremy
janl said 42 minutes ago:
seems sensible, can you open an issue?
Hello,
Inside of a partial, I have a value which is an array.
data: {
scales: ['1/10', '1/20', '1/50', '1/100', '1/200', '1/500', '1/1000'],
}
In my partial, I'm trying to loop through that array and to display all it's values.
"{{#scales}}{{.}}{{/scales}}"
It loops well. But the {{.}}
var is empty. So the value can't be displayed.
If I do the same outside of the partial, it works well.
{{.}} notation not working for Enumerables
puts
over print
, descriptions so rake -T
shows the possible commands:
I've created a test case to expose this issue. It's in another repository using the 0.2a HEAD commonjs branch build of Mustache.
Basically... with no template tag in the HTML the render will return an empty string.
http://github.com/davidjrice/node-comment/blob/master/test/test_mustache.js
I wasn't sure how to write a test in the Mustache.js style... so I wrote one the way the Node.js tests are written.
When a section key returns a function, it will be called and passed the block of text.
http://github.com/defunkt/mustache.js/compare/higher_order_sections
It would be nice to make mustache easily installable on Node. Right now the two parts that get in the way are the rake dependency and no package.json file. Thoughts on the best way to make mustache.js easily package-able?
This patch fixes the problem discussed in issue #27:
diff -r 478b4744a1a6 -r 6145973725ed README.md
--- a/README.md Sun May 23 20:02:43 2010 +0200
+++ b/README.md Thu May 27 18:49:58 2010 -0700
@@ -82,7 +82,7 @@
var view = {name: "Joe's shopping card",
items: ["bananas", "apples"]}
Outputs:
Joe's shopping card:
Hello,
When using partials, I don't always want to have datas in it.
However when there is a partial without any data of the same name, I get the following error :
Erreur : uncaught exception: [object Object]
Which is absolutely not readable.
And it'd be quite cool to manage that exception, and allow to display the partial even though there's no data associated with it.
Here is a commit with a few test cases that illustrate the problem and solution.
http://github.com/agibralter/mustache.js/commit/789bf588efea509cda55807d82f0a49b89c10c03
e.g.:
{{#items}}{{^first}}<div class="col gu1">
{{trailText}}
{{/first}}{{/items}}returns:
"true <div class=col gu1...........etc"
I added PRAGMA to Mustache tonight and thought it might be nice to support options, as ctemplate does.
For example:
{{%IMPLICIT-ITERATOR}}
{{#names}}
* {{.}}
{{/names}}
{{%IMPLICIT-ITERATOR iterator=_}}
{{#names}}
* {{_}}
{{/names}}
{{%IMPLICIT-ITERATOR iterator=bob}}
{{#names}}
* {{bob}}
{{/names}}
Could be interesting and allow for more flexible PRAGMAs.
i have a simple partial, template in the same dir.
tried both (where header.html.mu exists in the same directory as the main template.html.mu
nothing, works but doesn't include what is in header.html
This is the output I get from running the example, are array iterators broken?
Joe's shopping card: <ul> <li></li><li></li></ul>
var view = {name: "Joe's shopping card",
items: ["bananas", "apples"]}
var template = "{{name}}: <ul> {{#items}}<li>{{.}}</li>{{/items}} </ul>"
var html = Mustache.to_html(template,view);
Hey Jan -
I was hoping you could help shed some insight on this problem. I think it can be solved with the current implementation of Mustache, but I'm a bit clueless as to how to pull it off.
Imagine you wanted to generate a nested UL list based on some nested JSON data. I can currently pull this off with raw JS using something like:
this.render = function(values){
var str = '<ul>';
for(var key in values){
if(typeof values[key]=='object' && values[key] != null){
str+='<li>'+key+this.render(values[key])+'</li>';
}
else{
str+='<li>'+key;
if(values[key]!=''){
str+= ' : ' + values[key];
}
str+='</li>';
}
}
str+='</ul>';
return str;
};
return this.render(options.data);
What I'd like to see is this as a mustache template which would look like:
{{#list}} {{>listItem}} {{/list}}
I'm probably missing something simple here....I'm not a pirate as you know. :-)
Any suggestions / sample code would greatly appreciated. Thanks!
-Marak
if u pass the following to mustache:
data
{ "classname_passed_via_mustache": "a-dynamic-classname" }
tmpl
<div class='{{classname_passed_via_mustache}} a-static-classname\>...</div>
=> mustache returns:
<div class='a-dynamic-classnamea-static-classname'>...</div>
(there's no whitespace between both classnames!)
-dpree
I will provide a commit with a test and fix.
great work, janl :)
mustache.js (together with sammy.js) currently helps me alot..
however, i had many troubles with null-values:
http://gist.github.com/295904
cheers,
-dpree
Should mustache.js strip leading and trailing whitespace when interpreting partial names?
Hi,
Love mustache.js, been using it heavily on a project. One weird issue I ran into is I was trying to put a space before a conditional, but it seems to be flattening them. Well, only in some cases.
Here's an example:
http://gist.github.com/247989
If rowspan is true, it prints it, but without either of the spaces: the one preceding the conditional or the one within the conditional.
Basically all I want to ask is, am I doing it wrong? Any thoughts or suggestions would be greatly appreciated.
Thanks,
Jordan
blissdev said 2 days ago:
Ah, after some more testing, if I remove the preceding conditional, which I don't rely on at this point, then it seems to work. Maybe because it's two conditionals back to back? Maybe I'll try to investigate the code and see what's going on.
The render_section regexp strips leading whitespace in a section: {{#section} hello {/section}
produces "hello "
. Is that meant to happen?
current:
var regex = new RegExp(this.otag + "(^|#)\s_(.+)\s_" + this.ctag +
"\s_([\s\S]+?)" + this.otag + "/\s_\2\s_" + this.ctag +
"\s_", "mg");
proposed replacement:
var regex = new RegExp(this.otag + "(^|#)\s_(.+)\s_" + this.ctag +
"([\s\S]+?)" + this.otag + "/\s_\2\s_" + this.ctag +
"\s*", "mg");
{{!
Comments
should be allowed
to contain new-lines
}}
In my effort to make the ruby & js mustache compatible, I need to make the implicit iterators to_s.
Unfortunately, the ruby mustache blows up on {{%IMPLICIT-ITERATOR iterator=to_s}}.
I would like to make the default implicit iterator 'to_s'.
One way of doing it is to change Mustache.Renderer.prototype.pragmas. Unfortunately, Mustache.Renderer is private, so it would need to be public.
Another way is to have some sort of options method.
I would be fine with either. For now, I'll just make Mustache.Renderer public because it is less work.
Thanks,
Brian
Try this mustache:
{{=[[ ]]=}}
[[#IsMustacheAwesome]]
mustache is awesome!
[[/IsMustacheAwesome]]
[[={{ }}=]]
with this view:
{ IsMustacheAwesome: true }
It will render:
[[#IsMustacheAwesome]]
mustache is awesome!
[[/IsMustacheAwesome]]
when it should really render:
mustache is awesome!
At least that is what I infer from the documentation.
The problem is that by the time that the set delimiter is changed, render_section has already been long executed.
This issue combined with 44 and 45, make me think that a delimiter change should trigger a recursive render similar to sections and partials.
{{#outer}}{{inner}}{{/outter}} will yield
inner1...innerX\n
instead of
inner1..innerX
Sumbitted a test (simple_iterator) to show this.
when I call Mustache.to_html('x')
it returns 'x'
- when i call it a second time it returns 'x\nx'
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.