Django template inheritence - javascript

In my django app i have a base.html template as follows
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>{% block title %}{% endblock %}</title>
{# ----------------- STATIC FILES -------------- #}
{% load staticfiles %}
<link rel="icon" type="image/x-icon" href="{% static 'images/tab_logo.ico' %}"/>
{% block site_css %}
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"/>
<link href="{% static 'core/css/style.css' %}" rel="stylesheet" type="text/css"/>
{% endblock %}
{% block extra_css %}{% endblock %}
<meta name="viewport" content="width=device-width">
</head>
<body>
{% block navbar %}
<!-- START NAV -->
<nav role='navigation'>
<a data-page="home" id="home" class="active" href="/">Home</a>
<a data-page="blog" id="blog" href="{% url 'blog' %}">Blog</a>
<a data-page="contact" id="contact" href="{% url 'contact' %}">Contact Us</a>
<a data-page="about" id="about" href="{% url 'about' %}">About</a>
</nav>
<hr>
{% endblock %}
<!--start container-->
<div class="container">
<div class="row">
<div class="span9">
<div id="content">
<br>
{% block content %}{% endblock %}
</div>
</div>
</div>
</div>
<!--end container-->
<hr>
{% include 'core/footer.html' %}
{% block javascript %}
<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
<script src="{% static 'core/js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
<script src="{% static 'core/js/skin.js' %}"></script>
{% endblock %}
{% block add_js %}
{% endblock %}
</body>
</html>
I am trying to make separate template files for blog,about,contact
{% extends 'core/base.html' %}
{% block add_js %}
<script>
$(document).ready(skinchange('blog'));
</script>
{% endblock %}
{% block content %}
<h1 style="text-align: center;font-size: 32px;">BLOG</h1>
{% endblock %}
Now in the index page(nav bar home active), when i click on the blog link (Blog) redirection to localhost:8000/blog/ is done.When this page is loaded i want to change the class of nav a for blog to be active so that the style of the page is changed as per my css.For this i am executing a jquery script -> $(document).ready(skinchange('blog'));
where skinchange is a function in skin.js
'use strict';
function skinchange(page) {
page = typeof page !== 'undefined' ? page : 'home';
var link = $("nav a");
$("body").removeClass().addClass(page);
link.removeClass("active");
var d = document.getElementById(page);
d.className +="active";
}
for some reason on new page loading the class attribute of the nav links remains same as the base.html.The jquery script is not executing.
Can anyone help me what i am doing wrong here.

Related

Popup rendering with close button but it does not work when clicked?

I have a custom popup that shows upon form submission to let the user know it was successful. Currently it displays when it's supposed to (although I can't get it to display in the middle right on top, but that's a minor issue) like shown below:
But the little X button does not actually close the message. You can click it but it does nothing, and if you reload the page then it's gone until you submit again.
base.html
{% load static purchasing_tags humanize %}
{% include 'operations/message.html' %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="{% static 'images/favicon.ico' %}" type="image/x-icon" rel="shortcut icon"/>
<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="{% static "css/plugins/bootstrap.min.css" %}" rel="stylesheet">
<link href="{% static "css/apps.css" %}" rel="stylesheet">
<script src="{% static "js/plugins/jquery.js" %}"></script>
<script src="{% static "js/plugins/bootstrap.min.js" %}"></script>
<!--[if lt IE 9]>
<script src="{% static 'js/plugins/respond.js' %}"></script>
<![endif]-->
</head>
<body>
<div id="login" class="panel panel-default">
<div class="panel-body">
{% block main %}
{% endblock main %}
</div>
<div class="panel-footer">
{% block panel_footer %}
{% endblock %}
</div>
</div>
{% if messages %}
<script>
{% for message in messages %}
$(document).ready(function () {
$('.toast').toast('show');
});
{% endfor %}
</script>
{% endif %}
</body>
I think the problem could be related to the warning I get that says Unresolved function or method toast() on $('.toast').toast('show'); but I'm not sure how to resolve this issue (I got this from https://www.w3schools.com/bootstrap4/bootstrap_toast.asp but I don't know if I just didn't add something important to make this work)
enter_exit_area.html
{% extends "base.html" %}
{% load core_tags %}
{% block main %}
<form id="warehouseForm" action="" method="POST" class="form-horizontal" novalidate >
{% csrf_token %}
<div>
<div>
<label>Employee</label>
{{ form.employee_number }}
</div>
<div>
<label>Work Area</label>
{{ form.work_area }}
</div>
<div>
<label>Station</label>
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter" >Enter Area</button>
</div>
</div>
</form>
{% endblock main %}
message.html
{% for message in messages %}
<div style="position: absolute" class="toast bg-{% if message.tags == 'error' %}danger{% else %}{{message.tags}}{% endif %}" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
<div>
<strong class="mr-auto">
{{message.tags|capfirst}}
</strong>
<button type="button" class="ml-2 mb-1 close" aria-label="Close">
<span aria-hidden="true" data-dismiss="toast">×</span>
</button>
</div>
<div>
{{message|safe}}
</div>
</div>
{% endfor %}
views.py
class EnterExitArea(CreateView):
model = EmployeeWorkAreaLog
template_name = "operations/enter_exit_area.html"
form_class = WarehouseForm
def form_valid(self, form):
emp_num = form.cleaned_data['employee_number']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
if 'enter_area' in self.request.POST:
form.save()
EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True)).update(time_in=datetime.now())
messages.success(self.request, "You have entered")
return HttpResponseRedirect(self.request.path_info)

$().datepicker is not a function

I have added the datepicker function but I am not able to use it. I believe that it is I am doing some fundamental mistake since I am a beginner in javascript and jQuery.
The input tag is in the invite.html file which I am including using django's template tags all the jquery and semantic files I have downloded them in the static folder. I have added the datepicker.js files also I.Thanks in advance. I added and alert in the datepicker script it worked fine, So I think it is the function is added properly but
I get these errors:
jQuery.Deferred exception: $(...).datepicker is not a function
TypeError: $(...).datepicker is not a function
Scholarship.html is the main html file in which I have included the invite.html file and the input tag id="datepicker" is in bold in invite.html the fuction that is generating the is in bold.
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fusion!
{% block title %}{% endblock %}
</title>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'globals/semantic-ui/components/reset.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'globals/semantic-ui/components/icon.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'globals/css/semantic.min.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'globals/css/mediaquery.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'globals/css/semantic-notify.css' %}">
<script type="text/javascript" src="{% static 'globals/js/jquery.min.js' %}"> </script>
<script type="text/javascript" src="{% static 'globals/js/jquery.formset.js' %}"> </script>
<script type="text/javascript" src="{% static 'globals/js/semantic-notify.js' %}"> </script>
<script type="text/javascript" src="{% static 'globals/js/ajax-post.js' %}"></script>
{% block css %}
{% endblock %}
</head>
{% comment %}style="background-color: rgba(189, 189, 189, 0.1);"{% endcomment %}
<body id="body">
{% block body %}
{% block navBar %}
{% endblock %}
{% endblock %}
<div id="messages">
{% for message in messages %}
<div class="message" tag="{% if 'success' in message.tags %}green{% elif 'error' in message.tags %}red{% else %} blue {% endif %}" message="{{ message|safe }}"></div>
{% endfor %}
</div>
</body>
<script type="text/javascript" src="{% static 'globals/js/semantic.min.js' %}"></script>
<script type="text/javascript" src="{% static 'globals/js/dropdown.js' %}"></script>
<script type="text/javascript" src="{% static 'globals/js/tab.js' %}"></script>
<script>
$(document).ready(function() {
$('#messages').find('.message').each(function(){
$.uiAlert({
textHead: $(this).attr('message'), // header
text: '',
bgcolor: $(this).attr('tag'), // background-color
textcolor: '#fff', // color
position: 'bottom-left',// position . top And bottom || left / center / right
time: 3, // time
});
});
$('#new-notification')
.popup({
inline: true,
hoverable: true,
position: 'bottom left',
popup: $('#notificationPopup'),
on: 'click',
delay: {
show: 250,
hide: 500
}
})
;
});
</script>
Scholarship.html
{% extends 'globals/base.html' %}
{% load static %}
{% block title %}
Awards & Scholarship
{% endblock %}
{% block body %}
{% block navBar %}
{% include 'dashboard/navbar.html' %}
{% endblock %}
{% block winners %}
{% include 'scholarshipsModule/winners.html' with winners=winners %}
{% endblock %}
</div>
{% comment %}The Personal Details end here!{% endcomment %}
{% comment %}The Publications starts here!{% endcomment %}
<div class="ui tab segment" data-tab="second">
{% block invite %}
{% include 'scholarshipsModule/invite.html' with release=release ch=ch time=time awards=awards form=form %}
{% endblock %} *invite.html is included here*
</div>
</div>
</div>
{% comment %}The right-rail segment ends here!{% endcomment %}
{% comment %}The right-margin segment!{% endcomment %}
<div class="column"></div>
</div>
{% endblock %}
{% block javascript %}
<script src="https://cdn.rawgit.com/mdehoog/Semantic-UI/6e6d051d47b598ebab05857545f242caf2b4b48c/dist/semantic.min.js"></script>
<script type="text/javascript" src="{% static 'globals/js/datepicker.js' %}"></script>
<script type="text/javascript" src="{% static 'globals/js/tablesort.js' %}"></script>
<script type="text/javascript" src="{% static 'globals/js/editProfile.js' %}"></script>
<script type="text/javascript" src="{% static 'globals/js/modal.js' %}"></script>
<script>
$('.message .close')
.on('click', function() {
$(this)
.closest('.message')
.transition('fade')
;
})
;
**$( function() {
$( "#datepicker" ).datepicker(); This is the code that generates the error
} );**
</script>
{% endblock javascript %}
invite.html
{% load static %}
{% block winners %}
<div class="two fields">
<div class="field">
<label>Start date</label>
<div class="ui input large left icon">
<i class="calendar icon"></i>
**<input id="datepicker" type="text" name="From" placeholder="YYYY-MM-DD" required>
</div>**
</div>
<div class="field">
<label>End Date</label>
<div class="ui input large left icon">
<i class="calendar icon"></i>
<input type="text" name="To" placeholder="YYYY-MMM-DD" required>
</div>
</div>
<div class="ui divider"></div>
</div>
</div>
{% endblock %}
This is the datepicker.js fuction which is their in the globals/js folder
datepicker.js script
$('.rangestart').calendar({
type: 'date',
});
$('.rangeend').calendar({
type: 'date',
});
$(".date.calendar").calendar({ type: "date" });
You should add this below script into your site.. after that your error will be remove.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
$('#date1').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: "m/d/yy"
});
#ui-datepicker-div { font-size: 12px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"></script>
Date Picker: <input type="text" id="date1" name="date1"/> <br/>

Javascript doesn't work in django template

I have a template which inherits from a base template in javascript.
Here is the base template:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<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="">
<title>{% block title %}{% endblock %}</title>
{% include 'base/css.html' %}
{% block head %}{% endblock %}
</head>
<body id="page-top">
{% include 'base/navbar.html' %}
{% block content %}{% endblock %}
{% include 'base/js.html' %}
{% block js %}{% endblock %}
</body>
</html>
Here is the template where the javascript doesn't work:
{% extends 'base.html' %}
{% load static %}
{% block head %}
<link href="{% static 'css/card.css' %}" rel="stylesheet"></link>
{% endblock %}
{% block content %}
<div class="card-wrapper">
{% for account in object_list %}
<div id="make-3D-space">
<div id="product-card">
<div id="product-front">
<div class="shadow"></div>
<img src="" alt="" />
<div class="image_overlay"></div>
<div id="view_details">View details</div>
<div class="stats">
<div class="stats-container">
<span class="product_price">{{ account.price }}</span>
<span class="product_name">{{ account.get_arena_readable }}</span>
<p>King level {{ account.king_tower }}</p>
<div class="product-options">
<strong>SIZES</strong>
<span>XS, S, M, L, XL, XXL</span>
<strong>COLORS</strong>
<div class="colors">
<div class="c-blue"><span></span></div>
<div class="c-red"><span></span></div>
<div class="c-white"><span></span></div>
<div class="c-green"><span></span></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
{% block js %}
<script src="{% static 'js/card.js' %}"></script>
{% endblock js %}
The css loads fine, however the javascript doesn't. I have put the javascript tag in the correct block so the contents of the file should be loaded when I run the local development server. Why does none of the javascript get included?
It appears to be include since card.js is present.
Also in your base.html you have {% block js %}{% endblock %} but in the second template you have {% block js %}{% endblock js %}.
You are trying to access static files from static directory as described here:
<script src="{% static 'js/card.js' %}"></script>
Whereas in your settings you have named the static directory static_local
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static_local'),
]
So based on this image:
The name of your static directory is static.
So in your settings.STATICFILES_DIRS, replace static_local with static like the following:
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ]

Including block content between templates

I have a big problem with including blocks between templates. The code is following:
{# layout.html.twig #} (simplified version)
<html>
<head>
.....
.....
{% block stylesheets%}{% endblock %}
{% block javascripts %}{% endblock %}
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
{# index.html.twig #}
{% extends "demoBundle::layout.html.twig" %}
{% block content %}
some content {# <---- this is working #}
{% render(controller('demoBundle:Default:renderIndexContent')) %}
{% endblock %}
{# DefaultController.php #}
...
...
return $this->render('demoBundle:Gallery:slideshow.html.twig');
...
...
{# slideshow.html.twig #}
{% block stylesheet %} {# <---- this is not working #}
<link rel="stylesheets" href="{{ asset('bundles/cms/css/pictureSlider.css') }}"/>
{% endblock %}
The idea is, index.html.twig extends layout, and rendering another template with name slideshow.html.twig trought controller. But I need include stylesheets inner block in the template slideshow.html.twig to stylesheets block in head position in the main template layout.html.twig, but does not work. When i add tag {{ parent() }} to the block stylesheet in the template slideshow.html.twig, symfony say
Calling "parent" on a template that does not extend nor "use" another template is forbidden in demoBundle:Gallery:slideshow.html.twig at line 3
/EDITED*/
No, it is not resolution for me, because i have some variables returnet from defaultcontroller.php in template index.html.twig.
Ok, the previous code was just a simpliefed example. I enclose a concrete example
index.html.twig
{% extends "cmsBundle::layout.html.twig" %}
{% block rightSideBar %}{% endblock %}
{% block content %}
<div class="top_block">
<div id="module-1" class="no-title">
{% for block in blocksCenter %}
{% if (block.position=="center-top") %}
{% render(controller('cmsBundle:Default:renderIndexBlocks',{'blockname':block.name})) %}
{% endif %}
{% endfor %}
</div>
...
block.name is for example "slideshow". In the DefaultController.php inner method renderIndexBlocksAction is this piece of code:
DefaultController.php
return $this->render(
'cmsBundle:Blocks:'.$blockname.'.html.twig'
,array('items'=>$items)
);
this render template name slideshow.html.twig, there is this piece of code:
slideshow.html.twig
{% block styles %}
{{ parent() }}
<link rel="stylesheet" href="{{ asset('bundles/cms/css/pictureSlider.css') }}" type="text/css" media="all"/>
{% endblock %}
{% block javascripts %}
<script type="text/javascript" src="{{ asset('bundles/cms/js/jquery-1.11.0.min.js') }}"></script>
{% endblock %}
for completenes, her is the piece of layout.html.twig
layout.html.twig
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8">
<meta http-equiv="Content-Style-Type" content="text/css" />
<link rel="shortcut icon" href="{{ asset('bundles/cms/images/favicon.ico') }}" type="image/x-icon" />
<meta name="keywords" content="" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="{{ asset('bundles/cms/css/style.css') }}" type="text/css" media="all"/>
<link rel="stylesheet" href="{{ asset('bundles/cms/css/menu.css') }}" type="text/css" media="all"/>
{% block styles %}{% endblock %}
{% block javascripts %}{% endblock %}
</head>
<body>
<div id="bg_image"><img src="{{ asset('bundles/cms/images/AbstractBlue.jpg') }}" alt="" style="width:100%; height:100%;"></div>
<div id="mainContainer">
<div id="header">
<div id="top1">
<div id="logo">
<div id="search">
{% include 'cmsBundle:Default:search.html.twig' %}
</div>
<div class="wrapper" style="width:987px"/>
<div id="menu" class="menu">
{% render(controller('cmsBundle:Default:renderMenu')) %}
</div>
</div>
</div>
</div>
</div>
<div id="blocks" class="blocks">{% block rightSideBar %}{% endblock %}</div>
<!--CONTENT-->
<div id="mainContentm">
{% block content %}{% endblock %}
</div><!-- end #content -->
<!-- #footer -->
<div id="footer">
<div id="footer-left">
</div>
<div id="footer-right">
</div>
</div><!-- end #footer -->
</div><!-- end #container -->
</body>
</html>
The error itself says calling parent on a template that does not extend nor use means your template slideshow.html.twig is not extending any parent template or layout to follow thus if there is not parent template you cannot call the stylesheets of member that does not exist,for answer to your question in slideshow.html.twig use
{% extends '::index.html.twig' %}
and then define
{% block stylesheets %}
{{ parent() }}
<link rel="stylesheets" href="{{ asset('bundles/cms/css/pictureSlider.css') }}"/>
{% endblock %}
If there are any stylesheets in index.html.twig these will be included in your template,as viewing the index.html.twig code there is empty stylesheets block.If layout.html.twig has also defined a block for stylesheets then you should call {{ parent() }} function in the stylesheets block of index.html.twig so it will include the stylesheets of its parent layout i.e layout.html.twig

JavaScript loading twice in Symfony

When I am extending my base.html.twig my JS are loading twice. Here is my code:
{% block javascripts %}
{% javascripts
'#MyBundle/Resources/public/app/src/lib/jquery.js'
'#MyBundle/Resources/public/app/src/lib/jquery-ui.js'
'#MyBundle/Resources/public/app/src/lib/angular.js'
'#MyBundle/Resources/public/app/src/lib/ui-bootstrap-tpls-0.10.0.js'
'#MyBundle/Resources/public/app/src/lib/fullcalendar.js'
'#MyBundle/Resources/public/app/calendar.js'
'#MyBundle/Resources/public/app/src/lib/angular-route.js'
'#MyBundle/Resources/public/app/schedulePlanner.js'
%}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
I had a similar issue which turns out was caused by a misplaced {% endblock %} tag.
Here was my base view:
{# app/Resources/views/base.html.twig #}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>{% block title %}{% endblock %}</title>
{% block header %}{% endblock %}
{% block stylesheets %}{% endblock %}
<link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
</head>
<body>
<!--[if lt IE 9]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please upgrade your browser.</p>
<![endif]-->
{# debug #}
{% if pre is defined and pre is not empty and app.environment == 'dev' %}
<pre>
{{ pre }}
</pre>
{% endif %}
{% block body %}{% endblock %}
{% block javascripts %}{% endblock %}
</body>
</html>
And here was the bundle template that extended:
{% extends "::base.html.twig" %}
{# title #}
{% block title %}{% endblock %}
{% block header %}
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width">
<link href='http://fonts.googleapis.com/css?family=Pathway+Gothic+One' rel='stylesheet' type='text/css'>
{% endblock %}
{# style #}
{% block stylesheets %}
{% endblock %}
{# body #}
{% block body %}
{% block content_header %}
<div class="header"><div class="header-in">
<header>
</header>
</div></div>
<div class="nav"><div class="nav-in">
<nav>
<ul id="menu" class="menu clearfix">
{% block content_header_nav %}
{% endblock %}
</ul>
</nav>
</div></div>
{% endblock %}
<div class="block"><div class="block-in">
<div class="content"><div class="content-in clearfix">
{% set notices = app.session.flashbag.get('notices') %}
{% if notices is not empty %}
<ul class="msg ajax-flash-msg">
{% for notice in notices %}
<li>{{ notice }}</li>
{% endfor %}
</ul>
{% endif %}
{% block content %}{% endblock %}
</div></div>
</div></div>
<div class="footer"><div class="footer-in">
<footer>
{% block footer %}{% endblock %}
</footer>
</div></div>
{# javascript #}
{% block javascripts %}
<script src="{{ asset('assets/require.js') }}"></script>
{% endblock %}
{% endblock %}
You'll notice I had my javascript block inside of the body block in the bundle template which caused it to render twice upon html outputing to the browser.
To fix I moved the javascript block outside of the body block.

Categories