Newbie Node: referencing variables in javascript passed by res.render - node.js

If I have a module that returns runs this:
res.render('index', {
title:'Hello World'
});
I can access the title in jade by using #{title}.
How would I access it in separate .js javascript file included in the jade file?

To access a jade variable in an external JavaScript file, the variable must be declared in a script tag before you link to the relevant JavaScript file.
For example, if you have a script.js file that needs to access the title variable in jade, you could use the following code in your jade file:
script.
var jadeType = #{type}
script(type='text/javascript', src='./script.js')
The jade variable type can now be accessed in script.js using the JavaScript variable jadeType.
Hope this helps, if anyone is still looking for an answer to this question.

I'm not familiar with jade, but assuming you mean another javascript file included on the rendered page, then you can probably do something like:
<script type="text/javascript">
var title = '#{title}';
</script>

You can't reference those thingie in external js files, included in your jade template.
Please, have a look here: Accessing Express.js local variables in client side JavaScript

Related

Why res.render() doesn't send local variables to the client without template engine?

I need to access the variable user in my client-side that sent by
res.render('home.html', { user: req.user });
without using template engines like pug or ejs
Is that possible?
HTML is not a templating language, so it can't be used to send variables.
res.render() function compiles your template , inserts locals there, and creates html output out of those two things. The syntax is as follows -
res.render(view [, locals] [, callback])
The view argument is a string that is the file path of the view file to render. For this to work, you need a template or view engine .
In html, you can't dynamically pass/insert data variables. That's the main use case for templating engine. They put runtime/dynamic value in html which is what you are probably looking for.
In short, its better to use any template engine like pug,jade,ejs, etc most of which would have almost similar syntax with html to render dynamic html pages. I don't think there's any method (atleast simple enough) to send variables dynamically from server to client in an html page. Using a template engine would be the best choice in your use case.
For eg. you are passing user from server side and most probably want the passed variable to be rendered on the client side. You can just install an view engine like ejs - npm install ejs, set your view engine in app.js - app.use('view engine','ejs'); , and just add this line in the html page where you want to send the variable to client side like - <p> <%= user %> </p> and that's it. Keep your html file in view folder and this would do it.

how can we define static variable and call in html file in node.js?

I want to define variable in app.js file then after use this variable in whole/any html page.
Fore example:
app.js
var title = 'mytask';
index.html
<%=title%>
You can easily do the same using ejs
But if you want to use the varibale on hmtl page, you need to pass the title while rendering the page .
Say there is an "index.html"
res.render("index", {title :title});
now you can easily use the title variable in index.html
<div>{{title}}</div>
What you're looking for is called a local variable. If you're using Express (which I assume you do), then you have two kinds of locals, which are both sent to the views automatically, without passing them manually in each of your routes:
app locals: these are alive persistently for the entire lifetime of the application, you can use them anywhere where the app object is in scope. (more info)
response locals: these are tied to the lifecycle and scope of a single request/response object (more info)

How to get username injected into html?

I have a static html site:
index.html
I want to use handlebars {{username}} to inject a username variable. It looks like:
res.render('index', {username:'MyName'})
should work. The problem is my index.html is in my '/static' (my express.static()) directory. What is the best way to get my username variable into my html page without having to convert it to something that doesn't look like html? Thats why I dont want to use jade and prefer handlebars. If there is some other way, it would be best.
Update: I would like to preserve the same structure I have (keeping everything in my static directory) as opposed to moving things out to a "views" directory. Is this possible?
Then you must have to use Template engine. You can use Jade it also support HTML, only you have to use . at end of tag like:
doctype 5
html. // THAT DOT
<body>
<div>This is jade testing with HTML</div>
</body>
Is there a way to keep the file in my /static directory without having
to put it in the "views" directory?
Yes you can use _dirname while rendering
app.get('/anyurl/' , function(req, res){
res.render(__dirname + '/../static/path/folder') //modify path according to your structure
});

Dust.js partails newbie

I have piece of code which I want to use in some of the dust templates, so i am planning to use partials. I am not sure if following is the best approach. Please help.
1) I extracted common code from base templates in to a template file called userinfo.html
2) I compiled userinfo.html to create userinfo.dust
3) I added {>"userinfo.dust"/} code into all templates where I wanted to see user information.
4) Now when I render the template with following command. I get "Template not found: userinfo.dust" error.
dust.render("moduleTemplate", templateData, function(err, out) {
$main.html(out);
});
Do, I need to send userinfo.dust along with templateData while rendering? I tried reading all partial related information which google can give me, but not able to to figure how to implement partials.
In your template, when you call:
{>"userinfo.dust"/}
You should really be calling
{>"userinfo"/}
As yo don't need to specify the .dust extension. Here's a template example of mine:
{>header /}
{>results /}
{>footer /}
HTH
It sounds like the answer to your problem is that the partial is not being included on the page. Dust compiles to JavaScript, so this will make more sense if you rename your files: userinfo.dust (the template), and userinfo.js (the compiled template). Now include your template using a script tag:
<script type="text/javascript" src="templates/userinfo.js"></script>
Finally, you need to call the template using the svame name it was compiled with. It is a good idea to use the filename (often but not necessarily without the extension):
var userinfoCompiled = dust.compile('userinfo', 'user info template goes here');
A template compiled in this way can be called using:
{>userinfo/}
If you're not sure what your compiled template's name is, you can open the compiled JavaScript file and look for:
dust.register('userinfo')

how to use dustjs-linkedin as client side templating?

I get the idea of server and client side templating, but dust.js confuses me a little bit.
In order to use dust.js for client side templating, you need three steps:
complie the template
load the template
render the template
Right?
But where do the templates come from? I saw two different methods:
1. <script> template <script>
2. <div> template </div>
... Both of them are in the DOM. Which is correct?
I also notice that you can load the template via ajax, so the template won't be seen in the DOM, but I don't know how to do that.
Also, I'm currently using jade as express view engine. Is it necessary to switch to dust.js? What is the advantage?
This is LinkedIn Dust JS wiki page that can answer your questions and has very good examples: http://linkedin.github.com/dustjs/
But to answer your questions here:
Yes you need to compile your dust template which becomes a JavaScript file that you can add to your page by <script> tag and then call dust.render method to render your template. Here is an example:
write following code in a template file and save it as sample.tl
<p>Hi {firstName} {lastName}</p>
compile sample.tl to sample.js by dustc sample.tl in command line or use dust.compile("your_template_code", "template_name") to compile the template and save the output in a JavaScript file (sample.js) or you use duster.js to watch and compile templates by nodejs: https://github.com/dmix/dusterjs
add sample.js in your html:
<script type="text/javascript" src="sample.js"></script>
this will also register your template to dust.cache.
in your JavaScript:
var your_json = {firstName:'James', lastName:'Smith'};
dust.render('sample', your_json, function(err, out){
your_dom_element.innerHTML = out;
});
The result of above dust.render method will be <p>Hi James Smith</p>
So you need to pass 3 arguments to dust.render: dust.render(template_name, json, callback)
As the wiki say, you can use dust in the client or in the server. If you use it in the client you should get the template (for example with an ajax request), compile it an render in the browser. You will have to include the dust scripts file in your page.
By the other hand you can use dust in the server, (using rhino or nodejs). In this case you are going to compile and render the template in the server so the browser will receive html.

Resources