I'm working on a Django webapp and I need to pass data to the Javascript code (I use Require.js) when the page loads. Either I pass the data itself or information that I can later use for querying via Ajax.
I know I could create a global variable in my base.html template like this:
<script language="javascript">
var djangoData = "{{ data }}";
</script>
But it feels wrong to include it in the HTML and it won't be minified/uglified. I don't like to expose the inner logic so explicitly.
Ideally, I would have liked to create a Require.js module that will be populated with the relevant data from Django and that I can optimize (using r.js) and minify.
I would appreciate any suggestion.
Related
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 )
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!
I have written a basic API in PHP on my site (domain1.com). I need to load a simple form on another site (domain2.com) by placing a simple JS file on the other site. JS needs to access my API and format the form based on returned data.
Question: should I keep my JS file on initial site, with all the JS code in it and just let the other site include it like this
<script src="https://domain1.com/api.js?form=domain2"></script>
or shall I let the other site place a JS code, something like this:
<script>
var form = ... // send request to https://domain1.com/api/form
</script>
I'm sure it's a common knowledge, but I really never had to deal with this sort of issues, so, if you don't wish to answer, please don't mark for "close".
I have some javascript that's referencing /jobs/GetIndex in an MVC project. This works great when I run it locally because I have a Controller called JobsController. When I deploy it, I deploy the application to a 'Jobs' subfolder, which means the URL should become http://site/jobs/jobs/GetIndex but it's going to http://site/jobs/GetIndex, I presume because the javascript doesn't know what the 'root URL' is, and uses the site as the root. How can I get it to work in both environments?
If you simply care about getting the root/base url of the site so you can append that to get the other url you are after, you may simply use / as the first character of your url.
var urlToJobIndex2= "/jobs/GetIndex";
Here is an alternate approach if you want more than just the app root (Ex : Specific urls( built using mvc helper methods such as Url.RouteUrl etc)
You may use the Url.Content helper method in your razor view to generate the url to the app base, assign it to a javascript variable and use that in your other js code to build your other urls.
Always make sure to use javascript namespacing when doing so to avoid possible issues with global javascript variables.
If you want to get url to a specific action method, you may use the Url.Action or Url.RouteUrl helper methods.
So in your razor view (Layout file or specific view), you may do this.
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '#Url.Content("~")';
myApp.Urls.jobIndexUrl= '#Url.Action("GetIndex","jobs")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
And in your PageSpecificExternalJsFile.js file, you can read it like
var urlToJobIndex= myApp.Urls.jobIndexUrl;
// Or With the base url, you may safely add the remaining url route.
var urlToJobIndex2= myApp.Urls.baseUrl+"jobs/GetIndex";
Here is a detailed answer about the same , but using this in a specific page/view
Angular Js
You might need the correct relative url(s) in your angular controller / services / directives.The same approach will work for your angular code as well. Simply build the js namespace object and use the angular value provider to pass the data to your angular controllers/services/directives as explained in this post in detail with example code.
Add <base href="/jobs"> to your head tag. It will specify the root.
This is further explained here https://docs.angularjs.org/guide/$location
I added a JSON file to the assets folder in my Shopify liquid theme. I want to get and parse this JSON object in a jquery method from a javascript file in my assets folder. I've tried including the json file as an asset_url and I've tried using jquery's getJSON() method with the asset's path but the file can't be found. Does anyone know a good approach for adding a custom data object to a shopify liquid theme and the best way to access it?
You could save your JSON in a .liquid file and include it in your template. You'd define the JSON like this:
<script type="text/javascript">
window.my_json_obj = {
...
}
</script>
That way, you could access window.my_json_obj in your jQuery script. But if a key/value storage approach is enough for your needs, you should probably take a look at Shopify's metafields