Permalink
Browse files

Add in string interpolation to script and markdown helpers.

  • Loading branch information...
1 parent cdb4730 commit 8ba80770eff769070ac26ea4dcac53c330922c9e @creationix committed Feb 4, 2010
Showing with 49 additions and 3 deletions.
  1. +34 −3 lib/haml.js
  2. +3 −0 test/embedded_code.haml
  3. +7 −0 test/embedded_code.html
  4. +5 −0 test/embedded_code.js
View
@@ -7,7 +7,7 @@ if (exports) {
(function () {
- var matchers, self_close_tags;
+ var matchers, self_close_tags, embedder;
function html_escape(text) {
if (typeof text !== 'string') {
@@ -131,6 +131,37 @@ if (exports) {
return attributes;
}
+ // Split interpolated strings into an array of literals and code fragments.
+ function parse_interpol(value) {
+ var items = [],
+ pos = 0,
+ next = 0,
+ match;
+ while (true) {
+ // Match up to embedded string
+ next = value.substr(pos).search(embedder);
+ if (next < 0) {
+ if (pos < value.length) {
+ items.push(JSON.stringify(value.substr(pos)));
+ }
+ break;
+ }
+ items.push(JSON.stringify(value.substr(pos, next)));
+ pos += next;
+
+ // Match embedded string
+ match = value.substr(pos).match(embedder);
+ next = match[0].length;
+ if (next < 0) { break; }
+ items.push(match[1] || match[2]);
+ pos += next;
+ }
+ return items.join(" + ");
+ }
+
+ // Used to find embedded code in interpolated strings.
+ embedder = /\#\{([^}]*)\}/;
@claudiob

claudiob Mar 7, 2013

How can I have closing brackets } inside the interpolate code? For instance:

!{print_hash({'one': 1, 'two': 2})}

fails because the closing } of the Javascript hash is parsed as the ending of the interpolation

+
self_close_tags = ["meta", "img", "link", "br", "hr", "input", "area", "base"];
// All matchers' regexps should capture leading whitespace in first capture
@@ -288,15 +319,15 @@ if (exports) {
{
regexp: /^(\s*):markdown\s*$/i,
process: function () {
- return exports.Markdown.encode(this.contents.join("\n"));
+ return parse_interpol(exports.Markdown.encode(this.contents.join("\n")));
}
},
// script blocks
{
regexp: /^(\s*):(?:java)?script\s*$/,
process: function () {
- return JSON.stringify('\n<script type="text/javascript">\n' +
+ return parse_interpol('\n<script type="text/javascript">\n' +
'//<![CDATA[\n ' +
this.contents.join("\n ") +
"\n//]]>\n</script>\n");
View
@@ -0,0 +1,3 @@
+%head
+ :javascript
+ Page.chapter = #{JSON.stringify(chapter)};
View
@@ -0,0 +1,7 @@
+<head>
+<script type="text/javascript">
+//<![CDATA[
+ Page.chapter = {"name":"Ninja","page":42};
+//]]>
+</script>
+</head>
View
@@ -0,0 +1,5 @@
+{
+ locals: {
+ chapter: {name: "Ninja", page: 42}
+ }
+}

0 comments on commit 8ba8077

Please sign in to comment.