Skip to content

Instantly share code, notes, and snippets.

@danscotton
Created July 3, 2012 11:20
Show Gist options
  • Select an option

  • Save danscotton/3039157 to your computer and use it in GitHub Desktop.

Select an option

Save danscotton/3039157 to your computer and use it in GitHub Desktop.
refactoring our js templating using curl
======
BEFORE
======
This is how we currently do 'JS templating' when we want to insert
snippets of markup into the DOM: Strings of markup in an array,
using [].join(''); We then do String.replace() to replace the
{{placeholders}} with content.
// minihyper.js
define([
'module/bootstrap'
], function(
news
) {
var numMiniHyperpuffStories = 4,
miniHyperTemplate = [
'<aside class="pullout mini-hyper">',
'<div class="pullout-inner">',
'<h3 class="heading">{{title}}</h3>',
'<div class="related-items">{{content}}</div>',
'</div>',
'</aside>'
].join(''),
// ...
// do stuff with template below
// ...
});
=====
AFTER
=====
Alternatively, we can use curl and the text! plugin to reference a
.html file. (We don't currently have this, so maybe we could
rebuild to curl.min.js to include it...Tom?). This way, markup
stays as markup without having to wrap it in nasty quotes. We
can still keep the {{placeholder}} syntax as curl reads the html
file in as a string. Thoughts?
// minihyper.js
define([
'module/bootstrap',
'text!module/hyperpuff/minihyperTemplate.html'
], function(
news,
miniHyperTemplate
) {
var numMiniHyperpuffStories = 4;
// ...
// do stuff with template below
// ...
});
// module/hyperpuff/minihyperTemplate.html
<aside class="pullout mini-hyper">
<div class="pullout-inner">
<h3 class="heading">{{title}}</h3>
<div class="related-items">{{content}}</div>
</div>
</aside>
@danscotton
Copy link
Copy Markdown
Author

From requirejs.org:

The text files are loaded via asynchronous XMLHttpRequest (XHR) calls, so you can only fetch files from the same domain as the web page.

However, the RequireJS optimizer will inline any text! references with the actual text file contents into the modules, so after a build, the modules that have text! dependencies can be used from other domains.

I tried using text! for the mini-hyper template, but ran into the x-domain issue described above. I don't know whether we can set Access-Control-Allow-Origin on certain files for this?

As for the compilation, it seems it just converts it to a string. But that's not a problem, right? It was a string before using [].join() anyway...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment