JavaScript alert not working in Symfony Twig - javascript

This code is not executing JavaScript. What I need is when I click anywhere on the table with id="articles", an alert message should be displayed. I am using Symfony and Twig template. As suggested in the comments I have added base.html.twig also.
This is index.html.twig
index.html.twig
{% extends 'base.html.twig' %}
{% block title %}SymphArt Articles{% endblock %}
{% block body %}
{% if articles %}
<table id="articles" class="table table-striped">
<thead>
<tr>
<th>Article Title</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for article in articles %}
<tr>
<td>{{ article.title }}</td>
<td>Show
Delete</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No articles to display</p>
{% endif %}
{% endblock %}
{% block javascripts %}
<script>
var art = document.getElementById('articles');
if(art) {
art.addEventListener('click', e => {
alert("clicked");
});
}
</script>
{% endblock %}
Below is base.html.twig
base.html.twig
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}
{#{{ encore_entry_link_tags('app') }}#}
{% endblock %}
{% block javascripts %}
{#{{ encore_entry_script_tags('app') }}#}
{% endblock %}
</head>
<body>
{{ include('inc/navbar.html.twig') }}
<div class="container">
{% block body %}{% endblock %}
</div>
</body>
</html>

I believe your javascript is executing before your page is finished loading, so it is trying to find id="articles" before there is any.
Try wrapping your js code in a window.onload like this:
<script>
window.onload = function() {
var art = document.getElementById('articles');
if(art) {
art.addEventListener('click', e => {
alert("clicked");
});
}
}
</script>

Related

Link element tags are disabled when a background image is set

I've got this base.html from which other html documents extend
base.html
<!DOCTYPE html>
<html>
<head>
<--!some css links and jquery source headers-->
<style>
{% block style %}
.container{
position: relative;
}
{% endblock style %}
</style>
</head>
<body>
<div class="container">
{% block breadcrumb %}{% endblock breadcrumb %}
{% block content %}{% endblock content %}
</div>
</body>
<script type="text/JavaScript">
{% block script %}
var imgName = "{% url 'img_file.png' %}";
document.body.style.backgroundImage = "url('"+ imgName.src +"')";
{% endblock script %}
</script>
<\html>
a document that extends from base.html
index.html
{% extends 'base.html' %}
{% block breadcrumb %}
<div class="nav nav-bar nav-bar-dark>
some link
</div>
{% endblock %}
{% block content %}
<form action="view-url" method="post">
{{ form }}
<input type="submit" class="btn" value"Submit">
</form>
{% endblock %}
the submit input works well but the link (to some url) seems to be disabled. When I remove the background image from the base.html, the link works just fine. Any help on what I'm missing here please ,

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 %}

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.

Nunjucks dynamic page template

i'm using nunjucks (gulp) as templating language and i want to build a dynamic page template.
This is my Json:
"pages": [
{
uname: "Welcome",
title: "Page 1 Headline"
},
{
uname: "About",
title: "Page 2 Headline"
}
]
Currently i have a static page (html) template for each page:
{% extends "layout.html" %}
{% set active_page = "Welcome" %} //<- This needs to be dynamicly
{% block content %}
<h1>{{ page[0].title }}</h1> //<- This needs to be dynamicly
My first thought was to read the url parameters but i couldn't solve it in this way.
Any suggestions?
The solution was simple!
Need to do this:
index.njk
<!-- set title !!! -->
{% set title = 'home page' %} <!-- set title !!! -->
{% extends "layout.njk" %}
{% block header %} {% include "parts/header.njk" %} {% endblock %}
{% block main %}
<main class="main">
<!-- content -->
</main>
{% endblock %}
{% block footer %} {% include "parts/footer.njk" %} {% endblock %}
page1.njk
<!-- set title !!! -->
{% set title = 'page1' %}
{% extends "layout.njk" %}
{% block header %} {% include "parts/header.njk" %} {% endblock %}
{% block main %}
<main class="main">
<!-- content -->
</main>
{% endblock %}
{% block footer %} {% include "parts/footer.njk" %} {% endblock %}
layout.njk
<!-- layout.njk -->
<html lang="en">
<head>
<!-- here is the compiled title -->
<title>{{ title }}</title>
<link rel="stylesheet" href="styles/style.css">
</head>
<body class="page">
{% block header %}{% endblock %}
{% block main %}{% endblock %}
{% block footer %}{% endblock %}
</body>
</html>
If you are hoping to pass the data from data.json file
first you need to use someway to specify the page name in the data file itself.
Then you have to set the page name as a variable in the nunjucks page.
Now you can use this variable name to get the data relevant to the
page you are working in.
data.json
{
"pages": {
"welcome": {
"uname": "Welcome",
"title": "Page 1 Headline"
},
"about": {
"uname": "About",
"title": "Page 2 Headline"
},
}
}
index.njk
{% set pageName = 'welcome' %}
{% extends "layout.html" %}
{% set active_page = "Welcome" %}
{% block content %}
<h1>{{ page[pageName].title }}</h1>
{% macro inc(file, folder) %}
{% if folder %}
{% set folderPATH = folder %}
{% else %}
{% set folderPATH = file %}
{% endif %}
{% set path = folderPATH + "/" + file + ".njk" %}
{% include path %}
{% endmacro %}
{{ inc("menu") }} // {% include "menu/menu.njk" %}
{{ inc("content") }} // {% include "content/content.njk" %}

Django running a javascript function imported from parent, called by the child

I have a javascript file in an outside folder under static. My index.html is not running the javascript function that was imported from base.html.
File path:
-- project
-- app
-- templates
-- app name
-- index.html
-- src
-- static
-- hello_world.js
-- templates
-- base.html
View page source from browser
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
<script type='text/javascript' src="/static/hello_world.js"></script>
</head>
<body>
<div id="navigation">
<table border=0 cellpadding=7>
<tr>
<td>Home</td>
<td>Register</td>
<td>Login</td>
</tr>
</table>
</div>
<div id="content">
<h2> Welcome to WAM's board 2 player board games! </h2>
<canvas onload="entryPoint();" id="myCanvas" width="578" height="200"></canvas>
</div>
</body>
</html>
Base.html
{% block doctype %}<!DOCTYPE HTML> {% endblock %}
<html>
{% block head %}
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
{% load staticfiles %}
<script type='text/javascript' src="{% static "hello_world.js" %}"></script>
</head>
{% endblock %}
<body>
{% block navbar %}
<div id="navigation">
<table border=0 cellpadding=7>
<tr>
<td>Home</td>
{% if user_logged_in %}
<td>Upload</td>
<td>Challenge User</td>
<td>Logout of {{ user_name }}</td>
{% else %}
<td>Register</td>
<td>Login</td>
{% endif %}
</tr>
</table>
</div>
{% endblock %}
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
index.html
{% extends "base.html" %}
{% block navbar %}{{ block.super }}{% endblock %}
{% block content %}
<h2> Welcome to WAM's board 2 player board games! </h2>
<canvas onload="entryPoint();" id="myCanvas" width="578" height="200"></canvas>
{% endblock %}
Put this
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # already present in newest django versions
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
in your settings.py, or simply put your static files inside static folders inside app folders

Categories