share one or more variables to ejs file - javascript

I want to pass only one variable from a js file to ejs file.
I know about app.locals.Variable and about using <% include (./app.js) %> in the ejs file.
But , I don't want to include the whole app.js , only the specific one or more variables.

If using Express?
res.render('ejsfile', {
variable_for_ejs: source_of_variable
});

Related

I need help for connect js functions with ejs file

I wonder how I can insert JS functions into an EJS file?
I have this function:enter image description here
I tried to create a separate .ejs file where I will insert a function between the tags <% %> and also import it into the ЕЈS file that I need, but it doesn't work for me
EJS does not provide a DOM. Output from EJS is generated using <%= and similar.
The document object is only (that's a slight simplification) available in JS running in an HTML document in the browser.
To use that code you would need to include it in a <script> element output from the EJS into an HTML document and run in a browser.

How to pass data from nodejs to inside html script tags

I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?
static-pages-server.js:
app.get('/index', function(req, res) {
var name = "hello";
res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
});
index.html:
<script type="text/javascript">
console.log(name);
</script>
Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.
<script type="text/javascript">
console.log(<%=name%>);
</script>
Express.js itself is a backend server. If you would like to have dynamic HTML files you need to use templates engines.
Please follow this document -> https://expressjs.com/en/guide/using-template-engines.html
Eventually, you will realize you will need a frontend framework to write your code faster with good quality. So also recommend you to take a look at some of the frameworks like React, Vue.js. If you need Single Page Applications you only use express.js to provide data not to render HTML. If you need Server-side rendering it is good to investigate Next.js, Nuxt.js.
You cant directly inject variables into a html file in nodejs . That is why you have templating engines in express. Check out ejs.
It would allow you to pass data directly from your routes into the page you are rendering.
Local variables sent to a view via the locals parameter using the res.render() method aren't directly accessible. Instead you need to refer to those using it's variable name wrapped inside double curly brackets. So if you want to use it inside a JavaScript function, you need declare a local variable and give it the content of your name local.
Simply modify your index.html like this:
<script type="text/javascript">
let name = "{{name}}";
console.log(name);
</script>
here is the answer How do I use HTML as the view engine in Express?
what you will need is a view engine package in your app. there are many view engines currently available.
then set that view engine in express app. Trigger the view render via a call from your route’s response like you have done above.
Then in your view render the html output using the view variables and if these variables are outputted into html you can use them in your in browser JavaScript. You can also call a service in your html sending the dynamic data as well.
check out esj or pug (ps pug is my personal favourite )

How do relative paths to ejs templates work?

I am trying to render some ejs. I'm not using any frameworks. So right now I have an ejs navigation bar template and a template for a random other site (in this example it is just a form).
My directory:
root
rendered (cache for already rendered sites)
sites (ejs templates for sites)
form.ejs
test.ejs (template I am trying to insert into form.ejs)
templates (ejs templates for reusable stuff like the nav-bar)
bar.ejs
server.js (logic for the server: including rendering of ejs)
So now comes the actual question: How do I reference an other ejs template in an ejs template? The docs say:
%- include('user/show') %>
Includes ./user/show.ejs into the template (As I understood it relative to the current ejs file if no absolute path is given)
<% include user/show %>
is not supported after v3.0, but would have done (almost) the same.
So now I thought I could just do
<%- include('test') %>
in my form.ejs, but it throws an error:
Could not find the include file "test.ejs"
So I wondered what was going on and included the absolute Path to the file and voila it works.
I was curious so i included
<%- process.cwd(); %>
into form.ejs and that return the root directory probably because it is being executed from server.js.
So now the question is: How do I get relative paths? Do I have to create a variable at runtime with the root directory and add that to my include paths like this? (even this wouldn't be relative)
const root = process.cwd(); //inside server.js
<%- include(root+'/sites/test.ejs') %>
This seems inelegant. What am I missing? Thanks for your help.
Ok I'm guilty of RTFM: It didn't work before, because i had to set the views option in my ejs.render(str, data, options). With
ejs.render(contents.toString(),null,{views:["./sites"]}); //in server.js
<%- include('test') %> // in form.ejs ('test.ejs' works as well)
It now renders, but still, the path is relative to the one set in views.
Ok that's a workaround and after digging a bit more i found this line from the docs literally a line after what i originally posted:
You must specify the filename option for the template with the
include call unless you are using renderFile().
renderFile() is asynchronous, so that wouldn't work for me. So finally the solution is to modify my original ejs.render function:
html = ejs.render(contents.toString(),null,{filename: ejspath}); //ejspath being the path to the ejs file to render
//contents is the contents of the ejs file
This Method works with paths like ../templates.bar inside of form.ejs

NodeJS Render parameter to local JS

I am looking for an information.
How to pass a variable from NodeJS res.render('index', { title: "Hey"}) to local JS.
I use express (with helmet) and PugJs. I can include my var in the template, but I want to store it on the JS file who's part of the template. (No inline script, vanilla JS)
Currently, I use a hidden Input in the template to store the data, the JS script get the input and do the work.
How I can pass the variable thought the template to my JS file?
Sorry, I 'm French :(
Thank you for your time!

How to include js.erb file in view folder

I have a JavaScript file to use with a view. There needs to be Ruby code in it, and I need to do render in Ruby, so I understand that I can't put the JavaScript file in the asset pipeline. I can put it in the same view folder as the .html.erb file.
How do I include the JavaScript file, or use that JavaScript file for that view file? I tried javascript_include_tag in my view (that uses the asset pipeline apparently), using script src="myfile.js" for the myfile.js.erb file (but it can't find myfile.js), and names my js.erb file (users.js.erb) the same as my .html.erb file (users.html.erb), but all to no avail.
javascript_include_tag won't work js.erb declared in the view folder itself. There are three different ways you can have the javascript.
1] Write the code in the view, i.e., in the html.erb itself.
2] Create js file in public/javascripts folder and include it using javascript_include_tag.
3] In case you want to make the request as Ajax:
Create the js.erb in the view folder itself with the same name as that of the action.
In the view where some form is created which will be calling this action, make the request using :remote => true.
In the called action, use code as follows:
def action
respond_to do |format|
format.js
end
end
you can do this by
render :partial => "myfile"
you have to keep your file in controller's view directory with name _myfile.js.erb
Now you can write your own code (js,ruby) here and probably can separate out js with javascript_include_tag to avail asset pipline
This file will be first rendered by erb engine and then as javascript.

Categories

Resources