Cannot pass server object from one jade file to another jade file - javascript

I have just started using jade and node. I am passing an object from node to jade template (parent.jade) and including the same jade file (parent.jade) to another file (child.jade). it is depicted as follows:
Node part:
res.render('parent.jade', {data: mydata});
Then in parent.jade I am receiving the data correctly:
doctype html
html
head
title parent
script(type="text/javascript" src="/resources/file_javascript.js").
var data_from_node = !{JSON.stringify(data)}; //getting the data in javascript file
body(data-title="parent")
div#header(class="wrap")
include header.pug
ul#list(class="nav nav-tabs")
footer(id="footer" class="footer")
include footer.pug
In child.pug I am including the parent file but could not get the data object. I have tried everything but nothing is working here I am including it in the following way:
doctype html
html
head
title child.pug
body(data-title="child")
div(class="wrap")
include parent.pug //here I am including parent.pug getting the content right
div#mydiv(class="tab-content")
include table.pug
footer(id="footer" class="footer")
include footer.pug
script(type='text/javascript').
var data = !{JSON.stringify(data)}; //getting null here
script(type = "text/javascript", src = "/resources/file_javascript.js")
Is there any way to get the "data object" in child.pug from parent.pug because I am getting null in child.pug?

Unfortunately not. When you call res.render in Node.js, the context variables you pass to that template are only remembered while that template is being rendered. If you want to let child.pug have access to that variable, you must actively pass it to that template, as well (when you call res.render("child.pug", {...})).

Related

Get json from flask using an external js file

I have a flask server spitting out json data converted from pandas dataframe which look like:
[{'name': 'FBtr0075557',
'score': '164.00'},
{'name': 'FBtr0075557',
'score': '162.00'}]
The python code I'm using to convert the dataframe to json and serve in flask is:
result = df.to_json(orient="records")
parsed = json.loads(result)
return render_template('mirtar.html', targets=json.dumps(parsed))
When I use internal javascript, the data is parsed without any error:
<script type="text/javascript">
const targets = {{ targets|tojson }};
const entries = JSON.parse(targets);
console.log(entries);
</script>
However when I try to do the same using an external JS script, I get an error
Uncaught SyntaxError: Unexpected token { in JSON at position
From what I understand, the line const targets = {{ targets|tojson }}; in the external javascript doesn't behave the same way as in internal and the first '{' of the line is considered as an error.
I'm sure this is a very basic problem and there must be an easy way to do it that I have definitely missed.
Jinja syntax is only parsed in flask html templates, not externally loaded JS assets: because it's the python app doing the parsing, and in a deployed environment you'd typically serve static assets with a webserver like nginx.
The quickest way to sort this might be with this method where instead you use a data attribute within an HTML element. This appreciates that you're passing data to the template as an argument to render_template, so the data is present in the template at page load.
In your case this might look like
<!-- a hidden tag -->
<input type='hidden' id='targetid' data-thetargets='{{ targets|tojson }}' />
Then in your javascript load it up with:
var targets = JSON.parse(document.getElementById("targetid").dataset.thetargets);

How to use information sended by the controller in a JavaScript file using Spring Boot?

I'm using Spring Boot with the Thymeleaf template engine. I have a HTML called clients.html file in the templates folder and a JavaScript file called functions.js in the static folder. I want to send from the controller to the JavaScript file a List.
I have tried using this syntax in the JavaScript file:
let listaArticulos = /*[[${numeroArticulos}]]*/ [];
But I don't recive anything. I have tried using the script tag in the HTML and it worked, but I want to have the JS code in a separate file and not in a script tag with all my html code.
The controller where I send the information to the JS looks like this:
#GetMapping("/articulos")
public ModelAndView showHielo(#RequestParam(name = "numcli", required = false) String numcli){
ModelAndView mav = new ModelAndView(ViewConstant.ARTICULOS);
mav.addObject("numeroArticulos", searchMovimNumarts(" 133"));
return mav;
}
Where the controller send the searchMovimNumarts() method with the name of "numeroArticulos" the one returns a List.
And the JS file where I want to recive the "numeroArticulos" object looks like this:
/*This variable stores data sended by the controller*/
let listaArticulos = /*[[${numeroArticulos}]]*/ [];
console.log(listaArticulos);
I want to console log the content of the List using a JS file and no the html
tag. How can I solve this?
Thymeleaf template engine parses only the template file(html files). So you have to include those variables defined in the controller into the embedded js code. However You don't have to put your entire js code in your html. Have only that part of code that refer to those variables in script tag.
<script>
let listaArticulos = /*[[${numeroArticulos}]]*/ [];
</script>
and refer them in your external js after this
<script src="/js/externalscript.js"></script>

Django accessing non-static files from static files

I have a javascript static file within which I would like to specify a source url to a non-static json file. The below doesn't seem to work (the root directory here is the root directory of the django project):
source: {url: "users/username1/nonstatic.json"}
It works if I explicitly (and non-ideally) specify an absolute static json url:
source: {url: "static/default_GCMS.json"}
Am wondering what's the correct way of calling a non-static file from a static one (.js in this case).
So you want to call a django view from a static JS file. This is a rather common problem - to solve it you need to mix and match django template logic with static JS.
One easy solution would be to assign the URL of the view you'd like to call to a global JS variable in your django template before including your static JS file and then use that variable. So, your django template would be something like this
<script>
var g_djangoViewUrl = '{% url "my_django_view_url %}';
// Notice that g_djangoViewUrl is global (assigned to your window object) so will be visible from other JS files
</script>
<script src='the_js_file_that_will_use_the_url.js'></script>
The above has the problem that you'll need to remember to define the urls that will be needed before including your js files. A more structured and permanent solution would be to create a django-view whose only purpose would be to output a global object that would contain all the urls you are going to use from other JS files. So, you'll have something like this in your template
<script src='{% url "my_url_creating_view" %}'></script>
<script src='the_js_file_that_will_use_the_url.js'></script>
The my_url_creating_view should have a correct content type (application/javascript) and should just return a object like this:
var g_URLS = {
djangoView1: {% url "django_view_1" %},
djangoView2: {% url "django_view_2" %}
}
etc

Passing variable from jade file to javascript file

I am making a node express app. I am trying to pass a value from jade to a javascript file.
On the server side I am using:
res.render('index', { title: 'Title', test: 1 });
In my index.jade file I have the following:
script(type='text/javascript', src='http://code.jquery.com/jquery-1.9.1.js')
script(type='text/javascript', src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.js')
script(type='text/javascript', src='./javascripts/ui.js')
script(type='text/javascript', src='./javascripts/handle.js').
var data = !{test}
block content
h3= title
In my handle.js file I have
$(function() {
console.log(data);
});
On the console I get a message saying data is not defined. How do I pass the value of test from the jade file to the javascript file? Currently test is just an interger, but eventually it will be an object which contains a lot of properties.
How do I properly pass the value from the jade file to the javascript file?
That will only work for literals. For objects you can do this:
var data = !{JSON.stringify(data)};
As for the showing undefined part, check if its getting properly set and it is the correct variable.
Make sure you are loading in correct order:
script(type='text/javascript')
var data =!{JSON.stringify(test)};
script(src='./javascripts/handle.js)

Sending JSON and HTML page together in node.js

I am sending my HTML file to the client in node.js as shown below
app.get('/get', function(req, res) {
res.render(index.html);
});
Here, index.html refers to a json file.
How can I send both together or refer the json file in the client?
If you don't want to request the JSON file from the client as an independent HTTP request you can do one of the following:
Full server side rendering:
Use a template technology like moustache or handlebars, and try to render that data inline with the response. For example if you your JSON file returns a name and an address the index.html could look like:
<div>
<span>Name: {{name}} </span>
<address>Address: {{address}} </span>
<div>
Then when rendering you could pass a js object with properties name and address to the template and you wouldn't need to ask for the JSON file separately. This example follows moustache guidelines just in case I wasn't explicit enough.
Inline object
A bit like the previous solution but less elegant, you can add the full JSON response as an object with within a script tag, and then use it however you see fit. Try to append a block to he HEAD of index.html like this:
<script>
var myObject = <contents of your JSON object>
</script>
The other possible solution was just described in another answer.
I hope this helps.
HTTP only sends one resource at a time. If your page is requesting a JSON file, it needs to be served as a second request.
Alternatively, you can render HTML with a <script> block that has a variable assignment with your JSON-encoded data as a value.
You can't send two types of files back in a single request, but you could either do an ajax call in the html to get the json you need:
<script type="text/javascript">
var json_data;
$.getJSON("URL_HERE", function(data) { json_data = data; });
</script>
or add the json to the html as a javascript object via a template engine (jade shown below):
script(type="text/javascript").
var json_data = #{ JSON.stringify(JSON_OBJECT_HERE) }

Categories

Resources