New PHP-like JavaScript engine [sjs-4e]

2019-07-23

Writing HTML in JavaScript (ECMAScript v5.1) is not very pleasant.

Here is a typical sjs-4 code example:

var p = '';

p += '<div>';
    p += 'Hello from: <b>'+util.htmlEncode(f.title())+'</b>';
p += '</div>';

response.body(p);

It works, but it is ugly, especially if you throw even more HTML into the code. It would be so much nicer to embed the JS code into HTML, instead of the other way around.

This is precisely what the sjs-4e engine allows you to do. It is a dialect of the sjs-4 engine. Before executing sjs-4e code, it will be transpiled to sjs-4. Thus, you can use the same JavaScript API in both engines.

Here is the same code as above written in sjs-4e:

<div>
    Hello from: <b><?= f.title() ?></b>
</div>

Syntax

There are only a couple of syntax elements to be aware of:

  • Embed JS code: <? ... ?>,
  • escape and print the value of foo: <?= foo ?>,
  • print the value of foo (unescaped raw html): <?== foo ?>,
  • print to the output buffer within JS code blocks: print().

Docs

You can find more info and example code snippets in the sjs-4e docs.

Cheers,

Subscribe to our newsletter!