Use twig variables into ajax function - javascript

i have a personal mvc architecture and i want to use variables passed from the controller to the twig template into an included js file.
There are my files, All about the variable $server_ID :
DashboardController.php who send the $server_ID variable to the template
class DashboardController extends Controller {
public function get($id = null) {
$serverModel = $this->model('ServerModel');
$server_ID = $serverModel->findById($id);
$this->view('dashboard/get', ['server_ID' => $server_ID]);
}
public function ajax_getstats($server_ID) {
$return = ServerModel::getStats($server_ID);
echo json_encode($return);
exit;
}
}
Twig template main.html that make the layout
<!DOCTYPE html>
<html>
<head>
{% include 'head.html' %}
</head>
<body>
{% include 'header.html' %}
<div class="content">
{% block content %}{% endblock %}
</div>
{% include 'scripts.html' %}
</body>
</html>
scripts.html that include specific js files
<!-- Optional JavaScript -->
<script src="{{ ASSET_ROOT }}/assets/vendor/jquery/jquery-3.3.1.min.js"></script>
<script src="{{ ASSET_ROOT }}/assets/vendor/bootstrap/js/bootstrap.bundle.js"></script>
<script src="{{ ASSET_ROOT }}/assets/js/dashboard.js"></script>
And finaly dashboard.js where what i want to use the variable $server_ID
function getStats() {
var rStart = Date.now();
$.getJSON("http://localhost/site/public/dashboard/ajax_getstats/" + {{ server_ID }}, function(data)
{
// treatment here
});
}
$(document).ready(function()
{
getStats();
});

You can create a hidden input type in the main.html page which contains the value of server_ID, and then grab it in the JavaScript file.
main.html:
<!DOCTYPE html>
<html>
<head>
{% include 'head.html' %}
</head>
<body>
<input type="hidden" id="server-id" value="{{ server_ID }}"> <!-- This echos the server_ID variable to become the value for this input. -->
{% include 'header.html' %}
<div class="content">
{% block content %}{% endblock %}
</div>
{% include 'scripts.html' %}
</body>
</html>
dashboard.js:
let serverID = $("#server-id").val(); // This variable is now equal to $server_ID.
function getStats() {
var rStart = Date.now();
$.getJSON("http://localhost/site/public/dashboard/ajax_getstats/" + {{ server_ID }}, function(data)
{
// treatment here
});
}
$(document).ready(function()
{
getStats();
});

Related

Call a javascript function of base template from another template in django

in my base.html template, I write a function. Can I call it from another template?
I tried like this. It doesn't work.
base.html:
<!-- ...code... -->
<script>
function registration(){
if(document.getElementById("registration").className==='hide'){
document.getElementById("registration").className='show'
}else{
document.getElementById("registration").className='hide'
}
}
</script>
another template
{% extends 'base.html' %}
{% block body %}
<script>
//if i re write the function here, it works
registration()
</script>
{% endblock body %}
You can try like this in your base.html
<html>
<head>
<!---Here all the CSS links --->
{% block css %}
{% endblock css %}
<head>
<body>
{% block body %}
{% endblock body %}
</body>
{% block script %}
//write your script here
{% endblock script %}
</html>
in other template you have to just do like this
for example about.html
{% block body %}
{% endblock body %}

Symfony + Webpack using node packages inside templates

I am trying to implement Webpack Encore in my Symfony Project. I just added SweetAlert2 with node (npm i sweetalert2 --dev).
My "problem" is that I don't realize how to properly use this package once installed. I've been reading other questions but I don't understand where do I need to import it.
So far I've tried:
Creating a file inside /assets/js/swal.js. Also, I have tried with ES5 as well:
import Swal from 'sweetalert2';
export const swal = (message, type) => {
Swal.fire({
position: 'top-end',
icon: type,
title: message,
showConfirmButton: false,
timer: 1500
});
}
Add it to webpack.config.js as an Entry Point:
.addEntry('app', './assets/js/app.js')
.addEntry('swal', '/assets/js/swal.js')
Add it as an asset to the template with <script src="{{ asset('js/swal.js') }}"></script>. Maybe is worth to mention that I did try all the paths and PHPStorm does not recognize any of them.
Print the function or class inside Twig template:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}{% endblock %}
{{ encore_entry_link_tags('app') }}
</head>
<body>
{% block body %}{% endblock %}
{{ encore_entry_script_tags('app') }}
{% block javascripts %}{% endblock %}
{% if app.flashes is not empty %}
<script>
console.log(swal);
</script>
{% endif %}
</body>
</html>
I also tried importing it with require() but require is not idefined.
What should I do to implement this function and render it in the Twig template?
You can only import modules inside javascript (or typescript, etc) files.
let's say you have a function inside the script of the twig template:
<script>
function doSomethingBasic() {
// do your thing here, then alert the user using Swal
}
</script>
What you should do is export everything inside the javascript tag into a new .js file, inside the /assets folder.
After you create a new file inside the /assets folder with any name you want, you should add that entry to the webpack.config.js.
For example:
You created the newJavascript.js inside /assets.
Inside webpack.config.js:
.addEntry(`literallyAnyName`, `/assets/newJavascript.js`)
Then, in your twig template, substitute your script tags for this (must be the name you put in the webpack.config.js, in this case literallyAnyName):
{{ encore_entry_script_tags('literallyAnyName') }}
With this, you can import Swal in your newJavascript.js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}
{{ encore_entry_link_tags('literallyAnyName') }}
{% endblock %}
</head>
<body>
{% block body %}{% endblock %}
{% set flashes = [] %}
{% if app.flashes is not empty %}
{% for label,message in app.flashes %}
{% set flashes = flashes|merge([{
'type': label,
'message': message
}]) %}
{% endfor %}
{% endif %}
<div id="flashes" data-flashes="{{ flashes|json_encode|e('html_attr') }}"></div>
{% block javascripts %}
{{ encore_entry_script_tags('literallyAnyName') }}
{% endblock %}
</body>
</html>
newJavascript.js:
const flashes = JSON.parse(document.querySelector(`#flashes`).dataset.flashes);
// Maybe reduce the flash object into one message using flashes.reduce;
if(flashes.length > 0) {
const msg = flashes.reduce(/* your logic here */);
Swal.fire({
position: 'top-end',
icon: type,
title: msg,
showConfirmButton: false,
timer: 1500
});
}
This will trigger the second the page loads. You can make a button trigger as well if you need to.

running javascript in a nested component-like django partial template

I would like to make a "component" (several actually, but let us start with one). That is I would like to have a template file, which itself may include javascript. Then I would like to be able to include that "component" in whatever (other) Django template file.
Importantly: in the base.html I include utility javascript (like jquery or bootstrap or whatever) and I want those things to be in scope in the component's javascript.
Are there other achitectural ways of achieving this?
Here is a visual of one Django template:
and when an item is clicked, it will update the other part of the page, allowing that template and its included JS to run with access to the rest of the page's javascript.
Here is some code to go along with it (I mistyped base to baste, so I went with the theme):
models.py
class CommonTask(models.Model): ## nothing special
name = models.CharField(max_length=30, default='yummy')
urls.py
app_name = 'food'
urlpatterns = [
## the list view on the left
url(r'^edible/?', views.EdibleList.as_view(), name='edible'),
## the partial on the right
url(r'^billable/edit/(?P<jid>[a-zA-Z0-9-\w:]+)/?', views.EdibleEdit.as_view(), name='edibleEdit'),
views.py
class EdibleList(ListView):
template_name = 'food/edible-list.html'
def get_queryset(self):
return Dish.objects.filter('edible'=True)
class EdibleEdit(UpdateView):
form_class = EdibleForm
template_name = 'food/edible-edit.html'
def get_initial(self):
… # for the form/formset info
def get_object(self):
return get_object_or_404(Dish, pk=self.kwargs['pk'])
baste.html
<!DOCTYPE html>
{% load static %}
<html lang="en" xml:lang="en" dir="ltr" xmlns= "http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="{% static "css/main.css" %}">
{% block meta_tags %}{% endblock meta_tags %}
{% block scripts-head %}{% endblock scripts-head %}
<title>Edibles - {% block title%}{% endblock title%}</title>
{% block extra_head %} {% endblock extra_head %}
</head>
<body>
{% block content %} {% endblock content %}
{% block scripts %} {% endblock scripts %}
<script>
{% block script-inline %} {% endblock script-inline %}
</script>
<footer> FOOTER </footer>
</body>
</html>
list.html
{% extends "baste.html" %}
{% load static %}
{% block title%}Edible List - {{dish.name}} {% endblock title%}
{% block extra_head %}
<link rel="stylesheet" href="{% static "food/food.css" %}">
{% endblock extra_head %}
{% block script-inline %}
console.log('This works, as it is in the views original compiled template');
console.log('This does not work, as it relies on the partial to be loaded, but
the partial isn't loaded yet, and this wont update after the partial is loaded);
var interpuncts = document.getElementsByClassName("interpuncts");
for (let i=0; i < interpuncts.length; i++){
interpuncts[i].onclick=function(event){
console.log('gh1');
};
};
// showing the right partial when clicked
pane = document.getElementById("edible-single");
showPane = function(link) {
fetch(link).then(function(response) {
return response.text();
}).then(function(body) {
pane.innerHTML = body;
});
};
let edibleLinks = document.querySelectorAll("a.edible-link");
edibleLinks.forEach(function(edibleLink) {
edibleLink.addEventListener('click', function(e){
e.preventDefault();
showPane(edibleLink.getAttribute('href'));
});
});
{% endblock script-inline %}
{% block scripts %} {% endblock scripts %}
{% block content %}
{% include "food/nav.html" with currentView="edibleList" %}
<div class="container-fluid">
<h1 class="text-center">Edible Dishes</h1>
<hr>
<div class="row scrollable-row">
<div class="col-3 scrollable-col">
<table class="table">
<tbody>
{% for dish in dish-list %}
<tr class="d-flex">
<td class="col">
<a class="edible-link"
href="{% url 'food:ediblebleDetail'
pk=dish.pk %}"
data-pk="{{dish.pk}}">{{dish.name}}</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="col-9 scrollable-col" id="edible-single"></div>
</div>
</div>
{% endblock content %}
editPartial.html
{% load static %}
{# no blocks work in this, because it can't extend the list.html, because the view #}
{# can't render to endpoint(sibling) templates at the same time #}
{# {% block * %} #}
<script>
console.log('This won\'t run, as it is loaded separately as just an inclusion
text from the list AJAX call.')
$(document).ready(function() {
console.log('This can\'t work because it relies on $ to be accessible, which it is not')
var interpuncts=document.getElementsByClassName("interpuncts");
for (let i=0; i < interpuncts.length; i++){
interpuncts[i].onclick=function(event){
console.log('I can not get a handle on the partial template items after
they are loaded as a partial');
};
};
});
</script>
<div class="container">
Dish - {{dish.name}}
<hr>
<form action="{% form url %}" method="post">
{% csrf_token %}
{{ form }}
{# Some element(s) that needs some javascript to act on it, more comprehensive than #}
{# bootstrap show/hide can do #}
<div class="interpuncts">
··· Do something with this element
</div>
<input class="btn btn-primary pull-right" type="submit" value="Save">
</form>
</div>
NOTES:
This is similar to Rails' partials if I remember, and definitely doable in 'Angular/Ember'. I think this boils down to some architecture, or package I am unaware of and can't find documentation. I am unsure of it is doable with inclusion tags.

Can not trigger onclick function using Django, Python and JavaScript

I have an issue. I could not trigger the onclick event on the link using Django and Python. I am providing my code below.
base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{% load static %}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var query='';
function pageTransition(){
var full_url = window.location.search;
var url = full_url.replace("?", '');
query=url.file;
console.log('query',query);
var url="'"+query+"'";
$.getScript(url,function(){
$('a').velocity("scroll", { duration: 1000 });
})
}
</script>
</head>
<body>
<header>
<h1>Nuclear Reactor</h1>
{% if count > 0 %}
<b>Hi, {{ user.username }}</b>
Home
View Reactor status
logout
{% else %}
login / signup
{% endif %}
<hr>
</header>
<main>
{% block content %}
{% endblock %}
</main>
</body>
</html>
home.html:
{% extends 'base.html' %}
{% block content %}
<center><h1>Welcome</h1>
<p>This App allow to control the life cycle of the Nuclear Reactor and Retrive the status report </p>
<p>Status reportControl panel</p>
</center>
{% endblock %}
total html generated output after click on home link:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var query='';
function pageTransition(){
var full_url = window.location.search;
var url = full_url.replace("?", '');
query=url.file;
console.log('query',query);
var url="'"+query+"'";
$.getScript(url,function(){
$('a').velocity("scroll", { duration: 1000 });
})
}
</script>
</head>
<body>
<header>
<h1>Nuclear Reactor</h1>
<b>Hi, </b>
Home
View Reactor status
logout
<hr>
</header>
<main>
<center><h1>Welcome</h1>
<p>This App allow to control the life cycle of the Nuclear Reactor and Retrive the status report </p>
<p>Status reportControl panel</p>
</center>
</main>
</body>
</html>
Here I need to get that query string value and include it inside that JavaScript function but the JavaScript function is not called at all.

Using a Jinja2 for loop with a javascript alert

I've been trying to create a webpage where after receiving user input, it would display the history of all user input after pressing submit, however this is working as intended. However I wanted to implement an alert box which would show additional information. However as everything else is printed correctly, since the alert box uses an onclick event, it would only output the very last sample of user input.
<!doctype html>
<html>
<head>
<title>Enrolment page</title>
</head>
<body>
{% if all_users %}
{% for user in all_users %}
<h1> Hi, {{ user[0] }}) </h1>
<button onclick="myFunction()">Details</button>
<script>
function myFunction() {
alert("{{ user[1] }}, {{ user[2] }}");
}
</script>
{% endfor %}
{%else%}
No users to show
{% endif %}
</body>
</html>
In my code, all_users is the information from a csv file, however that is working fine. My only problem is the alert is not showing the information I want. Is there a way to store each set of user details in each script to print out each button since it is only displaying the last set of user details.
You can bind the user[0] and user[1] in the myFunction() call like:
{% for user in all_users %}
<h1> Hi, {{ user[0] }}) </h1>
<button onclick="myFunction('{{user[1]}}, {{user[2]}}')">
Detail
</button>
{% endfor %}
Then change the function to:
function myFunction(users) {
alert(users);
}
To work this in Jinja2, you might try using a string variable and appending each value as in (code not tested):
<!doctype html>
<html>
<head>
<title>Enrolment page</title>
</head>
<body>
{% if all_users %}
{% set AllUserList = "" %}
{% for user in all_users %}
{% set AllUserList = AllUserList + user[1] + ", " + user[2] + "\n" %}
<h1> Hi, {{ user[0] }}) </h1>
<button onclick="myFunction()">Details</button>
<script>
function myFunction() {
alert("{{ AllUserList }}");
}
</script>
{% endfor %}
{%else%}
No users to show
{% endif %}
</body>
</html>

Categories