Question: Does JavaScript have an equivalent to PHPs output buffering (start, get_clean)
or <<< EOF ... EOF
syntax to wrap inline HTML in a variable? Shims, libraries, functions, anything that gets the job done in modern browsers.
Why: I'd like to try to make a MVC framework in pure JS and the thought of creating blocks of HTML using strings or reading files and doing find/replace on keywords makes me wonder how efficient/maintainable the code would be.
Question: Does JavaScript have an equivalent to PHPs output buffering (start, get_clean)
or <<< EOF ... EOF
syntax to wrap inline HTML in a variable? Shims, libraries, functions, anything that gets the job done in modern browsers.
Why: I'd like to try to make a MVC framework in pure JS and the thought of creating blocks of HTML using strings or reading files and doing find/replace on keywords makes me wonder how efficient/maintainable the code would be.
To answer your question, no, JavaScript doesn't have anything like heredoc syntax. (CoffeeScript does, but ewww.)
You should take a look at how templating engines are implemented. I'm a fan of doT, which is very efficient. You define your template in a script
block, load the template source from there, and the engine piles it into a function. (One of the few legitimate uses of eval
.)
<script type="text/x-dot-template" id="mytmpl">
Hello, <b>{{=it.name}}</b>
</script>
var tmpl = doT.template($('#mytmpl').html());
tmpl({name:'test'}); // => 'Hello, <b>test</b>'
This keeps your markup out of your JavaScript and in the HTML, where it belongs.
No, JavaScript does not. The next version of ECMAScript has this as a proposal. But who knows when browsers will actually support it.
A mon alternative nowadays is to add a <script type="text/html">
block to your code (sometimes type is text/template
, this seems arbitrary) , and load that block using JavaScript. Many templating tools now do this. Since it's just an HTML tag, you can place whatever you want inside, no need to concat strings like a madman.
I don't know what you mean with "output buffering". Every action in JavaScript executes immediately, though some layout rendering might be delayed by the browser.
There is no EOF-syntay in Javascript, but you can escape linebreaks with a backslash:
"a\
b" === "ab"; // true
That might help for readability.