There is no native way for injecting JavaScript values into HTML by just using a tag like the PHP <=?
tag. What comes closest might be ES6 template literals.
It can look like this:
var mystring = 'Hello World';
document.write(`
<p>${mystring}</p>
<div>
some other stuff
</div>
`);
This version of JavaScript is available in most browsers today, but will of course not work in older browser versions, nor for current Internet Explorer versions (are we surprised?) -- but it works in Edge.
There are no native capabilities in HTML that allow injection of JavaScript values following the PHP-like syntax. In my opinion, the above comes as close as you can get. The only way to access to JavaScript variables from within HTML is with specific attributes (like "onclick") -- which serve another purpose --, and with script
tags, which do not work like the <?=
PHP tag either, but more like the standard <?php
tag.
Using templating libraries might be an option (e.g. mustache, underscore, EJS, handlerbars, pug, plates, dust.js, hogan.js, jsrender, markupjs, nunjucks...).
A simple, poor man's template library - class/content based
The above listed templating engines offer advanced features, but here is a very basic implementation that understands this kind of HTML:
<span class="template">`I want to say "${mystring}"`</span>
When the page loads, the "poor man's library" should render that as:
<span>I want to say "Hello World"</span>
Here is the code for doing just that:
/* my simple template library: you would include this from another JS file */
document.addEventListener("DOMContentLoaded", function(event) {
var templates = document.getElementsByClassName('template');
[].forEach.call(templates, function (template) {
template.textContent = eval(template.textContent);
template.setAttribute('class', '');
});
});
/* my set of variables */
var mystring = 'Hello World';
# my simple template CSS
.template {display: none};
<span class="template">`I want to say "${mystring}"`</span>
A simple, poor man's template library - attribute based
Here is variation on the same concept. Now the syntax is a custom tag inject
of which the value
attribute has the value to inject. Here it is the "library" that injects the template literal backticks. This could also have been done in the first version.
/* my simple template library: you would include this from another JS file */
document.addEventListener("DOMContentLoaded", function(event) {
var templates = document.getElementsByTagName('inject');
[].forEach.call(templates, function (template) {
template.textContent = eval('`' + template.getAttribute('value') + '`');
template.removeAttribute('value');
});
});
/* my set of variables */
var mystring = 'Hello World';
<inject value='I want to say "${mystring}"' />
{{myString}}
`. – Mar 23 '16 at 16:50