As we know in Django framework we can generate the HTML page based on some predefined template files.
Inside those templates we can use and some specific django keywords/operators/functions.
Like:
{% block stylesheets %}
<link href="{% static 'js/jquery/jquery-ui.css' %}" rel="stylesheet">
<link href="{% static 'vendor/chosen/chosen.css' %}" rel="stylesheet">
{% endblock stylesheets %}
But most important things which I want to touch in this question are related to tag 'translate'
"{% trans 'List of all available masters' %}"
So I can be sure that the final content of my page will use some predefined language.
And the places where I am using such tags are different: "simple" html content with / and etc tags AND inline javascripts blocks. Like:
<script type="text/javascript">
$('#datepicker_value').on('change', function(){
....
var dialog = BootstrapModalWrapperFactory.createModal({
title: '{% trans 'Extended information about the event' %}',
message: '<pre>'+JSON.stringify(info.event.extendedProps.description, null, 4)+'</pre>',
buttons: [
{
label: '{% trans 'Close' %}',
cssClass: "btn btn-secondary",
action: function (button, buttonData, originalEvent) {
return this.hide();
}
}
]
});
....
</script>
So my main question here is such:
HOW correctly I can move ALL <script>...</script> blocks from html template into the external JS file?
To keep all the functionality of the django framework working! And my 1 variant was - I should use the same technique which I use for generating HTMLs with Django framework abilities. But maybe in a little shorten variant: Right inside the views.py file - CAN I somehow correctly generate on the fly full content of GLOBAL.js file which will contains ALL ... blocks from html template - where they all were previously stored.
And in a such manner - that standard django template engine can convert all {% ..... %} placeholders in a correct real content BEFORE the full content of GLOBAL.js will be generated and given out. And especially the content of translatable placeholders!!! Well, then in the HTML page template I can insert a call to a special command that can display the contents of this script at the moment the page is rendered by the browser on the client side. Something like:
<script type="text/javascript" src="{% url 'GLOBAL.js' %}"></script>
Am i right? If yes - how I can do that step-by-step? Or maybe there is something new and more logical way?
Django version is the latest one!!! 3.*
P.S. Also I've faced with a problem of transferring script block with content like document.addEventListener('DOMContentLoaded', function(){...}); Looks like such event handlers can't be moved out to the separate JS file from HTML page((
There is no reason you couldn't use Django template tags inside Javascript files (or any other filetype for that matter). As an example, here's is a view that returns rendered Javascript:
from django.shortcuts import render
def render_javascript(request):
return render(request, 'myapp/global.js', {})
If you hook this view into your urlpatterns like this:
urlpatterns = [
path("js/global.js", render_javascript, name="globaljs"),
]
You can then use the {% url %} template tag to refer to it from your HTML templates like this:
<script type="text/javascript" src="{% url 'globaljs' %}"></script>
Now when your browser requests js/global.js, the Django view will take the template myapp/global.js, process it with the templating system, and return the rendered template.
Related
I've added the cookie consent code from here
It has
<script>
...
if(readCookie('cookie-notice-dismissed')=='true') {
{% include ga.js %}
{% include chatbutton.js %}
}
...
</script>
in the html. This is placed within _includes but I can't figure out how to include javascript like /js/foo.js, located in another directory. I believe this is bundled with bundler within the jekyll assets.
Up to now, I've added javascript on my layouts in the following way, but haven't used {% include %} for this yet and I don't know how to let the _includes/cookie_consent.html know แบhere to find it.
<script src="/js/foo.js"></script>
<script>
$(function(){
new Foo(".js-foo");
});
</script>
I can see two options to solve this
you create a file in _includes that contains the links to the extra JS you want.
For example:
# /_includes/bar.html
<script src="/js/foo.js"><\/script>
Inside _cookie_consent.html you can then add{% include bar.html %}
You add the link directly to your body.
if(readCookie('cookie-notice-dismissed')=='true') {
const js = '<script src="/js/foo.js"></script>'
document.body.appendChild(js)
}
I have a problem. I am doing all of this new fancy defer stuff when I load my JavaScript, as recommended by lighthouse while working on PWA.
{% block head_content %}
<script defer src={% static 'js/jquery.min.js' %}></script>
{% endblock %}
If I was just doing this in a Django tempalte, it would not be a problem, I could just move the <script> content to a .js file and defer that also:
{% block content %}
<script>
$( jquery thing
let x = 0; // Do jQuery stuff with NO json_data
);
</script>
{% endblock %}
However, I have a Django application that is doing something like:
{% block content %}
<script>
$( jquery thing
{{ json_data|safe }} // Do jQuery stuff with json_data
);
</script>
{% endblock %}
So if I try and move the script to a separate .js file I get: SyntaxError: expected property name, got {.
This very popular Q&A seems not to work if you get $ is not defined due to using defer, as noted by the top comment. Is my only option to put the script above the portion of the code that uses jquery in the body with no defer? If so, this limits the usefulness of Django's template inheritance.
{% block content %}
<script>
<script src={% static 'js/jquery.min.js' %}></script> // Add above each first-use of jQuery (along with every other relevant library)
$( jquery thing
{{ json_data|safe }} // Do jQuery stuff with json_data
);
</script>
{% endblock %}
I haven't been using Django in a while now, but I don't think you can "defer" that script tag inside your template. That said, you could try one of the following:
01: Load your json_data into a variable that you can access from an external .js file.
Something like:
var myJsonData = "{{ json_data|safe }}";.
Check this thread here for more info.
02: Another option is to create an endpoint that will return that json_data and call it from an external .js using ajax. Then you can use the data to do whatever you need.
Something like
$.ajax({
url: "my_django_endpoint",
success: function(result){
// Do jQuery stuff;
}
});
Check this thread here for more info.
We used a framework called T3JS that has a neat way of implementing Option 01 using context. (if you wanna take a look under the topic getConfig).
Hope it helps :)
So for those of us who use Python and Django framework to develop a website, there is this awesome tool known as jinja which can be used as a template engine. For example:
Instead of hard-coding an import like this:
<script src="assets/js/onebutton.js"></script>
We can do this:
<script src="{% static 'assets/js/onebutton.js' %}"></script>
In this case, it automatically searches for a folder named static and goes inside to look for the needed code.
But why isn't it possible to use jinja template in Javascript.
For example:
homepage.html
<script src='whatever.js'></script>
<p>Another example</p>
<button id="clickme"> click me </button>
whatever.js
$(function()
{
$('#clickme').click(function(){
$.ajax({
headers : {'X-CSRFToken': getCookie('csrftoken')},
type: "POST",
url: '{% url "func" %}', //<--Problem arise here
datatype:"json",
data: {},
success: function(data){
var new_template = '<h1> %firstmsg% </h1>';
var new_frontend = new_template.replace('%firstmsg%',data.message);
console.log(new_frontend);
document.getElementById('wor').innerHTML+=new_frontend;
}
});
}
}
Django would recognize the url in the AJAX request as /'{% url "func" %}' instead of /func
The only way to solve this is to move the entire code from whatever.js into the homepage.html in a <script></script> block.
Perhaps we need to import something for Jinja templating to work?
<script src="{% static 'assets/js/onebutton.js' %}"></script>
In this case, it automatically searches for a folder named static and goes inside to look for the needed code.
This is inaccurate. All it does is it converts the given path to the static path provided in your settings file like this - /static/asssets/js/onebutton.js. That is it. Django or Jinja2 doesn't go through the folder and look for the file. It doesn't even care if file exists or not.
Later, the browser automatically fetches this file from the server when it receives the html document.
Coming back to your original questions about why you can't use Jinja2 or Django template syntax in your JS files. Well, you can. But you'll have to render your JS files from your views.
Now, I'm sure you're using the render function to return a template from your views. But what does it do?
The render function converts the django specific template tags into proper html content.
So, if you're using django's or jinja's template syntax in your js files, you'll have to render your js files too. But that seems like a bad idea. Instead, you can create some global variables in your html files, and use them in your js files.
<!-- define required variables in template -->
<script>
var URL = '{% url ... %}';
var OTHER_VARIABLE = '{{ other_variable }}';
</script>
<!-- include your js files -->
<script src="/path/to/file.js"></script>
I have a workaround for this kind of necessities. Put your js code inside <script></script> tag and save it as html file inside templates folder.
Now you can include your html file to your page.
{% include 'myapp/js_code_with_jinja.html' %}
All jinja code will work as expected.
I am exporting HTML to PDF via Weasyprint in my Django app. I have noticed that if I send the template html to front end and return that html to backend to export it to pdf, it prints perfectly. But if I directly send template html to Weasyprint, it messes up everything! No css, no javascript.
This is how I'm using the template to generate html:
template = loader.get_template('Reporting/reportTemplate.html')
context = {
"reportObj" : result[0]
}
htmlContent = (template.render(context, request))
response['message'] = htmlContent
return JsonResponse(response)
In my JS controller I assign the htmlContent to my div:
$('#htmlContent').html(response.message);
Then I return the generated html back to my Django function to print pdf
HTML(string=htmlContent).write_pdf(target=response, stylesheets=[CSS(string=getCSS())])
This way it maintains the design and everything.
But when I send htmlContent directly to Weayprint without sending it to front end, the design and coloring is gone!
In my template, I even have included CSS and Javascript files like this:
{% load static %}
{% block content %}
<link href="{% static "css/ion.rangeSlider.css" %}" rel="stylesheet">
<link href="{% static "css/ion.rangeSlider.skinHTML5.css" %}" rel="stylesheet">
<script type='text/javascript' src='{% static "scripts/ion.rangeSlider.js" %}'></script>
<script type='text/javascript'>
$(document).ready(function(){
var creditScore = $("#creditScore").html();
$("#rangeCS").ionRangeSlider({
type: "double",
min: 0,
max: 1000,
step: 100,
from: 0,
to: creditScore,
from_fixed: true,
to_fixed: true,
grid: true,
grid_snap: true
});
});
</script>
{% endblock %}
How can I execute Javascript and CSS in Django template and export to PDF without having to send it to front end?
Are you meaning you've JS in the template that you render as source for Weasyprint ? Because JS used that way runs only on a client side (like browsers) and Weasyprint won't run it, it cannot. You must provided the final document (HTML) to Weasyprint.
If you've CSS issues in your PDF, so maybe you're using unsupported CSS features for Weasyprint.
Like mille_a said, you can't execute javascript code into a pdf.
So to resolve your problem you need to do it into your view :
# do some python stuff to get somes datas
datas = ...
# assign it into your html
htmlContent = my_html_template.render(datas)
# call the pdf generation
HTML(string=htmlContent).write_pdf(target=response)
You can see this example for more details : http://www.supinfo.com/articles/single/379-generate-pdf-files-out-of-html-templates-with-django
Hope it helps.
I've been trying figure out how to get a static website generator with built-in hash routing solution. I guess I could only describe it as a poor mans 'client side javascript framework with routing that works locally with out a server'.
My main goal is to avoid pages from being reloaded unnecessarily. While some pages would be refreshed, my hope is that the majority would not. Additionally, I still wanted to maintain page markup via markdown formatted pages.
I tried to do this with pure client side javascript and templates, but couldnt get any frameworks to parse markdown for me.
This is my hacked up solution perhaps some of you have a setup that works better or more elegant. Perhaps using Jekyll plus another routing framework like angular?
Note: I created a layout named 'empty' for hash routed pages because if the doctype, head, etc are duplicated then the pages will not load.
Problem: Files in other directories that load images - These files load images from their own directory, but when called via pagify.js to another directory their links are all broken
Jekyll + Pagify.js with Liquid include 'root' for relative urls (thanks to kikito):
root include:
{% capture root %}{% if page.root %}{{ page.root }}{% else %}{{ post.root }}{% endif %}{%endcapture%}
load scripts:
<script type="text/javascript" src="{{ root }}/js/jquery.js"></script>
<script type="text/javascript" src="{{ root }}/js/pagify.js"></script>
setup core html:
{% include root %}
<h1>Pagify.js<small>A jQuery plugin for single page web sites</small></h1>
<nav>
<a href='{{ root }}#about'>About</a>
<a href='{{ root }}#usage'>Usage</a>
<a href='{{ root }}#options'>Options</a>
<a href='{{ root }}#gallery'>Gallery</a>
<a href='{{ root }}#Showcase/VM'>Showcase</a>
</nav>
load script from pagify.js at end of core html:
<script>
$(document).ready(function() {
$('#page_holder').pagify({
pages: [
'about',
'usage',
'options',
'gallery',
'Showcase/VM'
],
animation: 'fadeIn',
'default': 'about',
cache: true
});
});
sample YAML heading from a hash routed page:
---
layout: empty
title : about
root: .\
---
{% include root %}
this is what the layout named 'empty.html' looks like:
{% include root %}
<div class="page-header">
<h1 class="well">{{ page.title }} <small>{{ site.tagline }}</small></h1>
</div>
{{ content }}
I created a Jekyll plugin to ease this process a bit. It takes away the need to manually specify all the pages you want to link to. Let me know what you think of it.