Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output buffer in JS?

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.

like image 224
Jonathan Avatar asked Nov 01 '25 02:11

Jonathan


2 Answers

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 compiles 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.

like image 105
josh3736 Avatar answered Nov 03 '25 15:11

josh3736


No, JavaScript does not. The next version of ECMAScript has this as a proposal. But who knows when browsers will actually support it.

A common 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.

like image 33
Matt Greer Avatar answered Nov 03 '25 17:11

Matt Greer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!