Use python variables in a external js file. Django - javascript

I'm working in a Django project and I would like to have it tidy. Thus I decided (among other things) don't have de css styles and js scripts inside the html templates. With the css styles I have no problems, I have created a css folder inside the static folder and I save all my css files inside, it works perfectly.
My problem comes when I want to do the same with the js files that works with the python variables that comes from the views.py. Because it don't recognise they. How can I import this variables to the js external files?
Now I have this, but it don't works.
main.html
{% load static %}
<!DOCTYPE html>
<html lang="es">
<head>
<title> {% block title%}{% endblock%} </title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="{% static "/css/main.css" %}">
<link rel="stylesheet" type="text/css" href="{% static "/css/data.css" %}">
</head>
<body>
<h1> WELCOME HOME </h1>
<p>{{Data}}</p>
/* This script has to be in a external js file. HERE WORKS
<script>
alert('{{Data}}');
</script>*/
{% block content %}{% endblock%}
<script type="text/javascript" src="{% static "/js/data.js" %}"></script>
</body>
</html>
data.js
alert('{{Data}}')
//alert({{Data}}) ERROR
If the alert has no python variables like alert("Hello world") it works well, but when I pass a Python variable it shows '{{Data}}'.
Thank you!

we can do this in two ways..
1.
add the below line in your html file
{{ value|json_script:"mydata" }}
and fetch the above value to data.js file as below
var value = JSON.parse(document.getElementById('mydata').textContent);
2.
add the following tag at the below of this line
<script type="text/javascript">
var data= '{{ data }}'
</script>
<script type="text/javascript" src="{% static '/js/token.js' %}">
</script>
and you can fetch it like as usual javascript variable as follows
in data.js file
alert(data);

you can pass it through function
try this
html :
demo({{var}})
js :
demo(var){
alert(var)
}
hope it helps

Related

How do you import a js file using {% load staticfiles%} in a base html template

Using Django {% load staticfiles %} I'm trying to load an app.js file in my base.html template.
I've seen several questions on StackOverflow about this and I also tried to follow this tutorial: https://www.techiediaries.com/javascript-tutorial/ but no of them actually helped with my issue.
It seems strange as well because on dev tools I see a 200 GET on the static/js/js.app and when I actually open the path the javascript is there.
Additionally, when I put the js code in a at the end of the body it seems to work. But I want to load the js from a file.
Below is the latest that I've tried, but still no luck.
base.html
<!DOCTYPE html>
<html lang="en">
{% load staticfiles %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'js/app.js' %}" rel="stylesheet">
<link href="{% static 'css/main.css' %}" rel="stylesheet">
<body>
<div class="container">
{% block content %}
{% endblock content %}
</div>
<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<!-- jquery -->
</body>
</html>
Settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
Put the following script after the body tag.
<script type="text/javascript" src="{% static 'js/app.js' %}"></script>
Why? When loading JavaScript files, it tends to fall under one of two cases.
The Javascript file contains functions which are needed while the page is loading OR
The Javascript file contains functions which should be used after the page is loading.
Conclusion
If the JS file contains functions referencing HTML elements then you should put it after the body tag so the page's DOM elements can finish loading first before the script. Else, putting it in the head works as well.
P.S - You should also consider performance, as there is a difference in that aspect when importing JS files in the head and after the body
Adding <script type="text/javascript" src="{% static 'js/app.js' %}"></script> below my </body> fixed the problem I had with the js file not loading.

Bootstrapp Affix Function

If I copy the code from W3Schools to my webserver then the "sticky" menu works as long as I am referencing the CDN path for the script and
stylesheet.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
If I change it to the location of the Bootstrap files that I have downloaded to the server then it doesn't work, although all other bootstrap
styles and javascript functions work when referencing the local files. I have tried downloading the latest from Bootstrap as well.
Sorry as I am probably missing something obvious, but is it possible to download the function and styles necessary for this to work?
i suggest try this: first you need set your static files in this case Bootstrap(css, js, etc):
static
....Bootstrap
......CSS
.........bootstrap.min.css
......JS
.........jquery-3.3.1.slim.min.js
.........popper.min.js
.........bootstrap.min.js
....etc
..etc
in this case we has the posible structure folder for static into this folder put the folder that content css an js files of bootstrap.
the next is set your links for css and js files in you template similar to this:
{% load staticfiles %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="{% static 'Bootstrap/css/bootstrap.min.css' %}">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="{% static 'Bootstrap/js/jquery-3.3.1.slim.min.js' %}"></script>
<script src="{% static 'Bootstrap/js/popper.min.js' %}"></script>
<script src="{% static 'Bootstrap/js/bootstrap.min.js' %}"></script>
</body>
</html>
now you need this on your settings.py:
..
..
..
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/static/',
]
...
..
that is all for load bootstrap or other static files in yout template, please try and good luck.
For download Bootstrap4 , 3..etc.. go to the official website:
Official site Bootstrap

Django 1.10 - Use django.shortcuts.render to generate a webpage with variables which includes a javascript as parameter

I'm new to Django, trying to migrate a website that I have built to a Django application.
I have generated an HTML template on which I want to present dynamic content based on the URL that was requested.
The HTML template looks like this:
{% load staticfiles%}
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
{{ script }}
</script>
<meta charset="UTF-8">
<link rel="stylesheet" href="{% static 'styles.css' %}"/>
<title>{{ title }}</title>
</head>
<body>
<header>
<h1>{{ title }}</h1>
</header>
<section>
<p>
{{ date }}<br/><br/>
SiteID: {{ site }}
<br/>
-----------------
</p>
</section>
</body>
</html>
On my views.py file, I'm generating the URL using this method (for example):
def site(request):
return render(request, "sites/site.html", {'date': strftime("%A, %B %d %Y"),
'site': '123456',
'title': 'Test',
'script': "window.lpTag=window.lpTag||{};if(typeof window.lpTag._tagCount==='undefined'){window.lpTag={site:'123456'||'',section:lpTag.section||'',autoStart:lpTag.autoStart===false?false:true,ovr:lpTag.ovr||{},_v:'1.6.0',_tagCount:1,protocol:'https:',events:{bind:function(app,ev,fn){lpTag.defer(function(){lpTag.events.bind(app,ev,fn);},0);},trigger:function(app,ev,json){lpTag.defer(function(){lpTag.events.trigger(app,ev,json);},1);}},defer:function(fn,fnType){if(fnType==0){this._defB=this._defB||[];this._defB.push(fn);}else if(fnType==1){this._defT=this._defT||[];this._defT.push(fn);}else{this._defL=this._defL||[];this._defL.push(fn);}},load:function(src,chr,id){var t=this;setTimeout(function(){t._load(src,chr,id);},0);},_load:function(src,chr,id){var url=src;if(!src){url=this.protocol+'//'+((this.ovr&&this.ovr.domain)?this.ovr.domain:'lptag.liveperson.net')+'/tag/tag.js?site='+this.site;}var s=document.createElement('script');s.setAttribute('charset',chr?chr:'UTF-8');if(id){s.setAttribute('id',id);}s.setAttribute('src',url);document.getElementsByTagName('head').item(0).appendChild(s);},init:function(){this._timing=this._timing||{};this._timing.start=(new Date()).getTime();var that=this;if(window.attachEvent){window.attachEvent('onload',function(){that._domReady('domReady');});}else{window.addEventListener('DOMContentLoaded',function(){that._domReady('contReady');},false);window.addEventListener('load',function(){that._domReady('domReady');},false);}if(typeof(window._lptStop)=='undefined'){this.load();}},start:function(){this.autoStart=true;},_domReady:function(n){if(!this.isDom){this.isDom=true;this.events.trigger('LPT','DOM_READY',{t:n});}this._timing[n]=(new Date()).getTime();},vars:lpTag.vars||[],dbs:lpTag.dbs||[],ctn:lpTag.ctn||[],sdes:lpTag.sdes||[],ev:lpTag.ev||[]};lpTag.init();}else{window.lpTag._tagCount+=1;}"})
The problem is, that this method actually renders all my strings so that it's escaping characters such as apostrophe ('), which is causing the JavaScript not to work. That's what I see in the browser console when running the page:
<script type="text/javascript">
window.lpTag=window.lpTag||{};if(typeof window.lpTag._tagCount===&#39;undefined'){window.lpTag={site:'123456'||'',section:lpTag.section||'',autoStart:lpTag.autoStart===false?false:true,ovr:lpTag.ovr||{},_v:'1.6.0',_tagCount:1,protocol:'https:',events:{bind:function(app,ev,fn){lpTag.defer(function(){lpTag.events.bind(app,ev,fn);},0);},trigger:function(app,ev,json){lpTag.defer(function(){lpTag.events.trigger(app,ev,json);},1);}},defer:function(fn,fnType){if(fnType==0){this._defB=this._defB||[];this._defB.push(fn);}else if(fnType==1){this._defT=this._defT||[];this._defT.push(fn);}else{this._defL=this._defL||[];this._defL.push(fn);}},load:function(src,chr,id){var t=this;setTimeout(function(){t._load(src,chr,id);},0);},_load:function(src,chr,id){var url=src;if(!src){url=this.protocol+'//'+((this.ovr&&this.ovr.domain)?this.ovr.domain:'lptag.liveperson.net')+'/tag/tag.js?site='+this.site;}var s=document.createElement('script');s.setAttribute('charset',chr?chr:'UTF-8');if(id){s.setAttribute('id',id);}s.setAttribute('src',url);document.getElementsByTagName('head').item(0).appendChild(s);},init:function(){this._timing=this._timing||{};this._timing.start=(new Date()).getTime();var that=this;if(window.attachEvent){window.attachEvent('onload',function(){that._domReady('domReady');});}else{window.addEventListener('DOMContentLoaded',function(){that._domReady('contReady');},false);window.addEventListener('load',function(){that._domReady('domReady');},false);}if(typeof(window._lptStop)=='undefined'){this.load();}},start:function(){this.autoStart=true;},_domReady:function(n){if(!this.isDom){this.isDom=true;this.events.trigger('LPT','DOM_READY',{t:n});}this._timing[n]=(new Date()).getTime();},vars:lpTag.vars||[],dbs:lpTag.dbs||[],ctn:lpTag.ctn||[],sdes:lpTag.sdes||[],ev:lpTag.ev||[]};lpTag.init();}else{window.lpTag._tagCount+=1;}
</script>
So my question is - How can I generate a dynamic page that is getting the actual JavaScript code as a variable without rendering the code? (Bear in mind that there are also simple texts that I'm transferring, such as the title of the page, so I will need to render the page anyway).
Thanks!
You should put that script in a separate file and then pass the file name to the template instead.
Put your script in a js file, say my_script.js:
window.lpTag=window.lpTag||{};if(typeof window.lpTag._tagCount==='undefined') ...
Then in your view:
def site(request):
return render(request, "sites/site.html", {'date': strftime("%A, %B %d %Y"),
'site': '123456',
'title': 'Test',
'script': 'my_script.js'})
Then in your HTML:
<head>
<script type="text/javascript" src="{{ script }}"></script>
<meta charset="UTF-8">
<link rel="stylesheet" href="{% static 'styles.css' %}"/>
<title>{{ title }}</title>
</head>

Django Static js files not working

Well my template code.
<!DOCTYPE html>
<html>
<head>
{% load staticfiles %}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="{% static 'website/staffaddproblem.js' %}"></script>
<title>Dashboard</title>
<link href="{% static 'website/style.css' %}" rel="stylesheet" type="text/css"/>
</head>
<body>
body
</body>
<html>
As you can see it has a css file. which is working properly, but java script file does not work.
when i load the page its source looks like this.
When i click the link it loads the file too its there its linking fine but its not working . there is no problem in code js code working fine when written in same file.
Have you changed the settings.py file to include staticroot?
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Here's a part of my template which works with both js and css files.
{% load static %}
<html>
<head>
<link type="text/css" rel="stylesheet" href="{% static 'css/materialize.min.css' %}">
<link type="text/css" rel="stylesheet" href="{% static 'css/stylesheet.css' %}">
<script type="text/javascript" src="{% static 'js/jquery-1.11.3.min.js' %}"></script>
<title>
The directories are as follows:
- static
-js
- jquery-1.11.3.min.js
-css
- stylesheet.css
- materialize.min.css
- templates
-index.html

External JavaScript file is not getting added when running on Flask

I have an HTML file named showMap.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Map</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript" src="js/map.js"></script>
</head>
<body onload="showPosition()">
<div id="map_canvas" style="width:500px;height:500px;"></div>
</body>
</html>
And another JavaScript file map.js is placed in the js folder of the same directory.
This code works fine when the HTML file is loaded, but this does not work when I run it in the server.
I use Python's Flask framework for back-end programming and the funny thing is that the same thing will work well if I expand the JavaScript code inside the HTML file. The only problem is with the external file.
Serve the map.js file as a static resource:
move the file to a static/ subdirectory of your package
generate a static URL for it in a Jinja2 template like so:
<script type="text/javascript"
src="{{ url_for('static', filename='map.js') }}"></script>
The filename parameter takes a relative path; you can use subdirectories was needed.
Step 1:
Create folder with name static on project root
Step 2:
Add static files in static folder
Step 3
Add in template
<script type="text/javascript" src="{{ url_for('static', filename = 'hello.js') }}"></script>
I experience the same issue, for stylesheet, the URL_FOR works but for javascript.
I had to write
<script type="text/javascript" src="static/map.js"/>
It worked for me
I want to add to Martijn's answer, that you have to link your js file exactly like this:
<script type="text/javascript" src="{{ url_for('static', filename='map.js') }}"></script>
and not like this:
<script type="text/javascript" src="{{ url_for('static', filename='map.js') }}"/>

Categories

Resources