I am developing a web server with node.js. But I got a problem just now.
Below code is my HTML code.
<%
var tagID = 'something';
%>
...
I know that if I use 'javascript:' inside a HTML tag. then it can execute javascript code. but it did not work when I checked it on my browser.
Or should I use DOM to do this?
You can use javascript: in a href. Like so
Hi
There are 3 ways to do what you are asking:
Using a single page application like angular, reacts ...
Use your own custom design pattern that will replace whatever you want to replace
var global = this;
global.id1 = 10;
global.id2 = 30;
document.querySelectorAll("*").forEach(function(dom) {
[...dom.attributes].forEach(function(attr) {
if (attr.value.startsWith("javascript:")) {
dom.setAttribute(attr.name, global[attr.value.replace("javascript:", "")]);
}
});
});
<div id="javascript:id1">Div 1</div>
<div id="javascript:id2">Div 2</div>
Do the update manually
document.getElementById("1").id = "10";
document.getElementById("2").id = "20";
<div id="1">Div 1</div>
<div id="2">Div 2</div>
If you are creating a big app then I would reccomand using a single page application (though it might take some time getting to know how it works if you are familiar with it).
If you are feeling adventurous or don't want to bother learning or using an SPA you could create your own framework/design pattern.
If the example you have shown is not a common occurence (and you don't expect it to be more common in the future), easiest solution would be to just manually update the dom.
You can use https://www.npmjs.com/package/ejs
// server.js
// load the things we need
var express = require('express');
var app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
// use res.render to load up an ejs view file
// index page
app.get('/', function(req, res) {
res.render('pages/index');
});
// about page
app.get('/about', function(req, res) {
res.render('pages/about');
});
app.listen(8080);
console.log('8080 is the magic port');
you can embed javascript like this
<ul>
<% drinks.forEach(function(drink) { %>
<li><%= drink.name %> - <%= drink.drunkness %></li>
<% }); %>
</ul>
<!DOCTYPE html>
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<body class="container">
<header>
<% include ../partials/header %>
</header>
<main>
<div class="jumbotron">
<h1>This is great</h1>
<p>Welcome to templating using EJS</p>
</div>
</main>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
Related
I'm working in a new web portal. So far using the express and node.js i have a server and some ejs files.
The body structure of my site is like this:
- node modules
- public
--javascript
---myScript.js
-views
--pages
---index.ejs
---about.ejs
--partials
---footer.ejs
---head.ejs
---header.ejs
package.json
server.js
server.js
var express = require('express');
var app = express();
app.set('view engine', 'ejs'); // set the view engine to ejs
app.get('/', function(req, res) {res.render('pages/index');}); // index page
app.get('/about', function(req, res) { res.render('pages/about');}); // about page
app.listen(8080);
console.log('Portal is listening to port 8080 ');
and the index.ejs
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<body class="container">
<header>
<% include ../partials/header %>
</header>
<main>
<div class="jumbotron">
<h1>MyPortal</h1>
<button>Press</button>
<% var test = 101; %>
</div>
</main>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
In the partials i want to call and use an external .js file /public/javascript/myScript.js so i can use variable from it in my ejs page or send a variable.
my js file have a simple function (just to see if it's working) that print in console if the button (in index.ejs) is pressed.
myScript.js
$(function() {
$("button").on("click", function () {
console.log("button pressed");
});
});
I'm trying to call the external js in head.ejs (or in index.ejs)...
<!-- views/partials/head.ejs -->
<meta charset="UTF-8">
<title>MyPortal</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>body { padding-top:50px; } </style>
<script type="text/javascript" src="/pubic/javascript/myScript.js"></script>
but i'm getting this error (in console)
Loading failed for the <script> with source “http://localhost:8080/pubic/javascript/myScript.js”.
Any idea why this happens and how to solve it?
Since you are trying to load client-side JavaScript, the fact you are using EJS is irrelevent. A standard HTML script element is all you need in the template, and you have that.
You do, however, need to provide a URL (with the src attribute) that the web browser can use to fetch the script … and your script has no URL.
You are getting the message Loading failed for the with source “http://localhost:8080/pubic/javascript/myScript.js”. because it is a 404 Error.
You should use the static module to provide the JS file with a URL.
app.use("/public", express.static('public'))
Add this to your server.js file,
app.use(express.static(__dirname + "/public");
And to link the js file with your ejs file,
Having this .html snippet:
<body>
<div id="testDiv">
This always appears
</div>
<%
if(step==1)
{%>
html code
<% }
if (step==2)
{
%>
other html code
<% } %>
</body>
How can I access the variable "step", present in a .js file, imported using a script tag, in order to show HTML elements conditionally?
I am trying to somehow simulate the *ngIf function of Angular2, in AspX.
Thanks!
You can use it like this and create a javascript variable.
<script type="text/javascript">
var step = <%= step %>;
alert(step);
</script>
You can also use a ScriptManager
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setValue", "var step = " + step + ";", true);
In both cases step is available in .js files.
I am attempting to load a javascript file onto my rails application, but only for a specific page in my application, not the homepage. How would I get my javascript file to load for a specific page is using rails.
The javascript I have now, located in programs.js in assets/javascript, looks like this:
document.addEventListener('DOMContentLoaded', (event) => {
let program = document.getElementsByClassName('program-name')
console.log(program)
})
Again, the code itself works fine. The problem is that it executes for the homepage, and not for any particular page that I want it to. How would I go about getting the code to execute for a specific page within my rails application?
Why wouldn't you add the javascript tag to the View you want it to run on?
If you wanted a bit better rendering speed, you could add a end-of-page yield to your layout and then specify your javascript in the View like this:
layout/application.html.erb
<!DOCTYPE html>
...
<%= yield(:scripts) %>
</body>
</html>
view/.../index.html.erb
<!-- regular view code here -->
...
<% content_for :scripts %>
<%= javascript_tag do %>
document.addEventListener('DOMContentLoaded', (event) => {
let program = document.getElementsByClassName('program-name')
console.log(program)
});
<% end %>
<% end %>
An other way is to do the following:
app/views/layouts/application.html.erb
<body class="<%= controller_name %> <%= action_name %>">
<!-- This will add your page's controller and action as classes, for example, "blog show" -->
Then, in your script file, you can do the following:
if($('body').is('.yourcontroller.youraction'){
// Do something
}
So I have index.ejs which renders perfectly when I start my nodejs server:
<!DOCTYPE html>
<html>
<head>
<title<%= title %></title>
</head>
<body>
<h1><%= title %></h1>
<h3><%= yesterday %></h3>
<h1> Number of Spins: <%= count %></h1>
<h1> Active User Count: <%= userCount %></h1>
<h1> Users that did not validate: </h1>
<ul>
<% for(var i=0; i<unvalid.length; i++) {%>
<li><%= unvalid[i] %></li>
<% } %>
</ul>
</body>
</html>
The thing is, I would like to send this on an email using Sendgrid. So far what i've been doing is using the .setHTML method to sort of "brute-force" it:
email.setHtml('<h1> Spotluck Daily Report </h1><h3>'+ yesterday + '</h3><h1> Number of Spins: '+cuenta+'</h1><h1> Active User Count: '+userCount+'</h1>' +'<h1> Users that did not validate: </h1>');
But this would never work because it would be unable to render the ejs for loop. So my question is: How do I tell the Sendgrid email to render my ejs and send it as an email without having to resort to .setHTML?
You can achieve this using the ejs.render(str, subs) function inside of setHtml.
email.setHtml(ejs.render(yourTemplate, {foo: 'bar'}));
But I'd recommend using SendGrid's Template Engine since our node library supports it.
Lets say I have a simple view
<html>
<head>
<title>something</title>
</head>
<body>
<%= param %>
</body>
<script type="text/javascript" src="myscript.js"></script>
</html>
And here's myscript.js
$(function() {
var p = <%= param %>
}
Can I make express rendering engine (in this case ejs) render inside myscript.js ?
I don't believe express will touch your static files. You could make this a view that gets rendered and served from a route, as in:
app.get('/js/myscript.js', function(req, res) {
res.render('myscript');
});
With regex routes, you could do this with anything ending in .js. (Before anyone downvotes, note that I said could, not should.)
You probably would be better off with static javascript being served to the browser that uses JSON data served from Express, though.