EJS: pass a variable to the included file - ejs

I'm using EJS as a part of my front-end dev stack.
For example my normal index.ejs looks like that:
<%- include parts/header.ejs %>
<%- include parts/navigation.ejs %>
<!-- HTML content: divs, spans, etc. -->
<%- include parts/footer.ejs %>
What I want is to pass somehow a variable with the include <%- include parts/footer.ejs?variable=value %> and want to read it in the included file, to conditionally show/hide some parts of the content.
I can't find the way to do it. Is it possible with EJS?

Two ways to do this:
Dumb Way
This way is compatible with EJS 1.0, and has the advantage of being compile-time.
Just declare the variables right before includeing.
Example:
included.ejs:
<p><%= variable %></p>
main.ejs:
<% var variable = 'hola' %>
<% include included %>
Smart Way
This method is only available with EJS 2.0 or newer, but might be marginally slower (or a lot slower if caching is not enabled) than the last method:
included.ejs:
<p><%= variable %></p>
main.ejs:
<%- include('included', {variable: 'hola'}) %>

Related

EJS includes not working

I have an EJS file called 'test.ejs', which contains:
<p>This is a test statement</p>
Then, I have another file called 'index.ejs' which is in the same folder as the other EJS file. Index.ejs contains:
<%- include ("test") %>
<p>Hello world</p>
However, when I load the page, I do not get any output. Instead, the page just loads endlessly.
My routes in Express are being handled properly and my controllers are working too. All this is tested.
Also, can someone refer me to good EJS documentation?
Try this:
<% include ./test %>
<p>Hello world</p>
try: <% include /pathname/test %>
Documentation is sparse but the official one works
http://www.embeddedjs.com/
or
http://ejs.co/

how to include a template with parameters in EJS?

As a real beginner in EJS, I have two charts in my html page, so I want to use my partial twice:
<% include partials/spider-chart.ejs %>
But I need to pass some parameters inside the ejs to differentiate between graphs.
What is the best way?
#Naeem Shaikh solution works.
Though include also gives you more intuitive way of including a partial template and also passing context variables to that as found in documention section of ejs.
<ul>
<% users.forEach(function(user){ %>
<%- include('user/show', {user: user}); %>
<% }); %>
</ul>
I think you want to render two different charts using same partial ejs template, just by providing different data(within the main ejs file).
You can just define a variable, which will be assigned to the data, which the first chart will use, than include the chart.ejs file, again change the data, and include the partial ejs file(chart.ejs) again, so now you have two files which can use same variable(data), but can plot different chart based on value assigned to data.
For Example:
<% var data= 'data to be used by first chart(parameter)'; %>
<% include partials/spider-chart.ejs %>
// re-initializing data for second chart
<% data= 'data to be used by second chart(parameter)'; %>
<% include partials/spider-chart.ejs %>
where your spider-chart.ejs file could be something which will use data
spider-chart.ejs
<li>
<%= data %> // just an example
</li>
here, as you use data, the data variable accessed by both charts will be different because you are reassigning values for data before every chart.
You can pass single as well as multiple data here is how to do it
In render funtions
We can pass multiple data as an object like this
app.get("/account", function(req, res) {
res.render("account", {
name: 'Jon Snow',
age: 35
});
});
And then can access the data inside account using ejs simple template tags like this
<h2> hello <%= name %> </h2>
<p> your age is <%= age %> </p>
In Partial views
Pass the data like this
<%- include('partials/logout', {name='triyon'}) %>
And access it like we did above
<h2> logged out <%= name %> </h2>
This is the best workaround by just passing the view file name as a context while rendering the base ejs file.
/base.ejs:
<html>
<%- include(content) %>
</html>
/extra.ejs:
<div> some content which is to be added in base ejs file </div>
/controller.js:
res.render('base', { content: 'extra' })

Why Isn't The Partial File Automatically Created?

Getting through Michael Hartl's tutorial great; I've encountered a few snags along the way but nonetheless, it's working out better than I expected.
My question, is regarding the partial file. In the tutorial if I have read correctly, chapter 5- it advises to edit the 'application.html.erb' file with...
'<!DOCTYPE html>
<html>
<head>
<title><%= full_title(yield(:title)) %></title>
<%= stylesheet_link_tag "application", media: "all",
"data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
<%= render 'layouts/shim' %>
</head>
<body>
<%= render 'layouts/header' %>
<div class="container">
<%= yield %>
</div>
</body>
</html>'
The tutorial then says if this line worked I should find a file called 'app/views/layouts/_shim.html.erb' and I cannot find it, thus, it was not automatically created, further not allowing me to pull up the referring static page in my browser (which may or may not be related).
Thanks in advance.
Of course, to get the partial to work, we have to fill it with some content; in the case of the shim partial, this is just the three lines of shim code from Listing 5.1; the result appears in Listing 5.10.
So yes. You have to create partial file by yourself and fill it with proper content. In case you code editor doesn't support partial extraction.
For example:
Using rails.vim plugin for VIM there is the possibility to extract selected lines into partial by using Rextract <partial_name> command. Which creates new file, moves selected lines into it and replace selected lines from source file with <%= render :partial => '<partial_name>' %>

HTMLHelper.Beginform query

I'm learning about HTMLHelpers in ASP.NET MVC.
To render the form HTML tag you would write something like
<% using(Html.BeginForm("HandleForm", "Home")) {%>
<!--Form content goes here-->
<% } %>
or
<% Html.BeginForm(); %>
… Form Contents …
<% Html.EndForm(); %>
To render the a checkbox you would use
<%= Html.CheckBox("bookType") %>
What I would like to know is is why we need to use <% when we use BeginForm whereas we need to use <%= when we use other HTMLHelper methods
Cheers,
Html.CheckBox returns a string of HTML containing an <input> tag.
You need to print this string to the page by writing <%= ... %>.
Html.BeginForm prints the HTML inside the method (by calling Response.Write), and doesn't return HTML. (instead, it returns an IDisposable, so that you can use it in a using block)
Since you aren't printing its return value, you put it in a <% ... %> block, which executes code without printing its results.
<% %> wraps a code block
<%="string" %> is equivalent to <% Response.Write("string") %>
and in ASP.NET MVC 3 you can automatically HtmlEncode with <%: "<htmlTag>" %>
You can definitely write <%=Html.BeginForm() %> but you will also need to write <%=Html.EndForm() %>. Wrapping Html.BeginForm() within a using block will just render the closing </form> tag for you.
Because <%= means "Print this for me", pretty much the same as doing:
<% Response.Write("content"); %>
When <% means that you have a code-block that might do more than just print the value you have nested in it.

MVC2 Custom HTML Helper and <%: %> Syntax

Is there any way to use a custom html helper with the <%: %> syntax ?
I know that if i'm use the code below, it's ok, but it's seems not so elegant and secure.
<%= Html.MyHelper("Some Data")%>
I mean, use <%= %> is the best practices?
Have your helper return an MvcHtmlString instead of a string. Also, please use <%: as much as possible.
HTML helpers create HTML, which is normally expected to be output raw with <%= %>. If you used <%: %> to HTML-escape the output of an HTML helper, you'll see the HTML source it produced on the page as text (eg literally <input name="foo" value="bar"> on-screen), which is probably not what you want.
It is up to the helper to HTML-escape any text content inside them, for safety. Yes, if you write a custom HTML helper and get it wrong—forgetting to HTML-encode strings your helper is putting in text content or attribute values in the output—you'll have security holes. You need to know what you're doing with escaping to write an HTML helper.
Microsoft, unfortunately, apparently don't, as the very first example in their tutorial completely fails:
return String.Format("<label for='{0}'>{1}</label>", target, text);
Whoops. Hope those ID and text strings didn't come from untrusted data!
[why are web tutorials always so lamentably terrible at escaping issues?]