Reputation: 12532
Currently or futurely, is possible merge HTML and Node on same file, like PHP does? Currently I know that we need use a template file or util.print()
, but for very simple cases, exists other solution, like ... ?
<?node var util = require("util"); ?>
<strong>Hello <?node util.print("World"); ?>!</strong>
Return:
<strong>Hello World!</strong>
Upvotes: 0
Views: 84
Reputation: 3760
Jade lets you prepend code with a -
to run it serverside, so
-var a = 1;
script.
var a=2;
will produce a variable named a
on the client with a value of two and on the server with a value of one. Obviously, you could do non-trivial stuff too, but as a simple example, that's the closest analogue I can think of to the PHP <? ?>
syntax.
Or like in your analogy:
-var W="World";
strong Hello !{W}!
Will produce:
<strong>Hello World!</strong>
in the browser.
Check out the language docs here, although as fair warning, Jade templates only have access to the variables passed to them by the View that invokes them or variables explicitly declared global in other modules (to the best of my knowledge) so something invoked elsewhere might not scope properly, and the template logic will be run each time it's loaded...
So yeah, while you could do it, I'd be careful.
Upvotes: 1
Reputation: 92
You can assemble and send HTML on the server side, but you can't access Node from the client side. You probably want to read into Jade/EJS- you end up passing variables to the client side that you can access to do your PHP-style logic.
Upvotes: 0
Reputation: 26690
Node.js itself does not support this out of the box, but there are several frameworks (including the popular Express.js) that do. Look for "templates" for Express.js and you'll see several options to do this including EJS (embedded JavaScript) and Jade.
http://expressjs.com/guide.html
Upvotes: 2