vue.js with Django-webpack-loader - javascript

I want to use vue.js with Django but get stuck how to integrate vue in the Django templates.
I manage to make a bundle with webpack, setup vue with a piece of html which I can open 'as file' in the browser and then vue components are shown. So that is working properly.
However when I run my Django server I get the tag and not the Vue component:
Maybe I am on the wrong track as I see others working with an Django REST api and then you might work differently with your templates. But I would prefer first to just integrate vue in my existing Django templates if possible!? I that possible and how should it be done?
test_html:
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Webpack Sample Project</title>
{% render_bundle 'main' %}
</head>
<body>
<h3>[[ message ]]</h3>
kiekeboe
</body>
</html>
main.js:
import '../css/custom.css';
import Vue from 'vue';
Vue.config.delimiters = ["[[", "]]"];
new Vue({
el: 'body',
data: {
message: "Hello Vue"
}
});
Further info:
I am currently using: https://github.com/owais/django-webpack-loader which includes all css, sass, other js libraries etc. via a render-bundle tag. As you can see the css-styling does come through, so I think vue tags should work in same manner?! Furthermore also static files from Django static folder can be used 'the normal way'. When putting the bundle.js in static folder and referring to it as:
<script type="text/javascript" src="{% static 'main-890ab68c2f63dd3f9a2a.js' %}"></script>
it DOES work. So why not via Django-webpack-loader?

I noticed that the vue.js reference needs somehow to come after the vue html tags. Same applies when using Django-web-loader, so {% render_bundle 'main' %} needs to go down. This got it working:
{% load staticfiles %}
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Webpack Sample Project</title>
</head>
<body>
<h3>[[ message ]]</h3>
kiekeboe
{% render_bundle 'main' %}
</body>
</html>

Related

Import repetitiv HTML fragments in to other html files using node.js

I have a Node.js project with multiple html pages. I want to lower the repetitiveness of code fragments in each file, e.g. the head tag/fragment will stay the same in every file, with a title and some css stylesheets etc.
I want my index.html file to looks something like this...
import head.html
<body>
<div>
<p>hello world!</p>
</div>
</body>
import footer.html
... head.html file to look something like this...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<link rel="stylesheet" type="text/css" href="/static/css/stylesheet.css">
</head>
... footer.html to look something like this...
<footer>
*some div with copyright stuff*
</footer>
How will I achieve this using node?
Use a templating engine. I'm a fan of Nunjucks, but there are many alternatives.
It's include syntax is very similar to your hypothetical version.
{% include "html.html" %}
<body>
<div>
<p>hello world!</p>
</div>
</body>
{% include "footer.html" %}
(Note, however, that the <footer> should be inside the <body>).
Then you just write a little code to combine them:
const nunjucks = require('nunjucks');
const index = nunjucks.render('index.html');
// Then write index to a file or whatever
You might want to use an existing static site generator or use nunjucks as a template engine for Express.

Use python variables in a external js file. Django

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

Use VueJs local file instead of importing it

I have been learning VueJs through single file application at the first start.
It would consist in a single html page containing my javascript & CSS style within.
In order not to import the VueJs features from the web I have downloaded the Vue.JS file and linked it into the HTML file by inputing:
<head>
...
<script src="vue.js"
...
</head>
By doing this I was able to add a <script>...</script> into my HTML file, that consists in the JS code that would recognize Vue.
It worked just fine.
Now I want to split the code into their respective files:
HTML file
JS file
CSS file
Now I am confused to what should I import at the <head> section of my HTML file, as I need to import my file.js that contains my code + I will want to have my Vue.js file running so I don't need to import vue.js from the web.
What should I do?
I have tried the following but it did not work:
<head>
<title>First Vue playground</title>
<link rel="stylesheet" href="style.css">
<!-- Below is my JS code-->
<script src="appJS.js"></script>
<!-- below is my vue.js file so it runs Vue locally instead of importing it-->
<scrip src="vue.js"></scrip>
</head>
It's a basic question as it is my first time doing this.
Thanks to all in advance.
If you intend to use Vue in the file appJS.js, you will need to first import the vue.js before your file. here is how your files should look like :
App.js
window.onload = function () {
var app = new Vue({
el: '#app',
data: {
message: 'hello vue'
}
});
}
Index.html
<!DOCTYPE html>
<html>
<head>
<script src="./scripts/vue.js"></script>
<script src="./scripts/app.js"></script>
<title>Vue Test</title>
</head>
<body>
<div id="app">
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<p>{{ message }}</p>
</div>
</body>
</html>

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>

angular JS installed but not loading, in Django app

I have a practice app and Angular JS installed through NPM on my machine at work. I call it in my base.htm which all templates extend:
{% block main_header %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sitename</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css" rel="stylesheet">
<link href="{% static "screen.css" %}" media="screen, projection" rel="stylesheet" type="text/css" />
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script type="text/javascript">
{% block js %}{% endblock %}
</script>
</head>
{% endblock %}
I just tried reinstalling it to be certain, it is installed. At
http://www.w3schools.com/angular/tryit.asp?filename=try_ng_default there is an example, and I put it in my django app at business_index.html as so:
{% extends 'base.htm' %}
{% block body_block %}
....some code
<div ng-app="">
<p>Input something in the input box:</p>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>
</div>
{% endblock %}
The some code beforehand isn't the problem, I temporarily deleted it and refreshed. Why is my text not displaying next to hellp like in the example? I must not have configured it well. Thank you
If you have never worked with Django + AngularJS before, I will assume that you are trying to use {{ variable }} in your template.
That syntax will try to render a Django variable from the view (passed by context_data).
You will need to change the AngularJS tags:
myModule.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
});
EDIT
Example:
var MyApp = angular.module('MyApp', []);
myApp.config(function($interpolateProvider){
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
});
After you do this, when you want to call a variable or angular expression in your template you will use {[{angular_variable}]}, and when you want to call a Django variable you will use {{django_variable}}
Also you can see this answer and the AngularJS documentation for this topic

Categories

Resources