I have a base.mako template with a if statement to include or not jQuery
<head>
% if getattr(c, 'includeJQuery', False):
<script type="text/javascript" src="jquery.js"></script>
% endif
...
Several templates inherit from base.mako, someone needs jQuery, someone don't.
At the moment I have to set the attribute in the controller before calling render
c.includeJQuery = True
return render('/jQueryTemplate.mako')
but I think this should go directly in child template (i.e. jQueryTemplate.mako)
I tried adding it before inherit
<% c.includeJQuery = True %>
<%inherit file="/base.mako"/>\
but it does not work.
Any tips?
Thanks for your support
You shouldn't be using "c" in your template.
<% includeJquery = True %>
and
% if includeJquery:
...
% endif
should suffice.
I think you are doing this wrong... In your base template you should make a blank def for a jquery block and call it. Then in the inherited template just redefine the block.
base.mako:
<head>
${self.jquery()}
</head>
<%def name="jquery()"></%def>
Then in another template you add jquery with:
<%inherit file="base.mako />
<%def name="jquery()">
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
</%def>
Well, since with the line
<script type="text/javascript" src="jquery.js"></script>
I also need to add some other js I put a jQueryScript %def in child template
##jQueryTemplate.mako
<%def name="jQueryScript()">
<script>
</script>
</%def>
then in base I check if exists and add all accordingly
#base.mako
%if hasattr(next, 'jQueryScript'):
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
${next.jQueryScript()}
%endif
so I don't need to set nothing in the controller.
Related
I tried to integrate this(having a layout.html and index.html) into my app. Before starting I only had index.html with all of my css/javascript includes at the top.
Current file struct
/app
- app_runner.py
/templates
- layout.html
- index.html
/static
/styles
- mystyle.css
Layout.html (mostly css and javascript CDN and my stylesheet)
<!doctype html>
<!-- Latest bootstrap compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional bootstrap theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- jquery -->
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<!-- Latest bootstrap compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- jstree -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<!-- my stylesheet -->
<link rel='stylesheet' type='text/css' href="{{url_for('static',filename='styles/mystyle.css')}}" />
<script type="text/javascript">
var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
{% block body %}{% endblock %}
The page, for the most part, renders the same: The jstree appears, bootstrap works, and the rest of my styling is applied. In my css file I have a line that doesn't get applied:
td {
padding: 5px;
}
The developer console shows padding:0, which comes from a bootstrap script. If I change it in the developer console I can get it to change to 5px.
I've heard using !important is bad practice but I tried it anyway with no change. I tried adding a class to all my td so it'd have higher precedent (based on this answer) and have that style (.my_row{padding:5px;}) apply but again it doesn't change. So it seems my css isn't being applied to my table. Other parts of mystyle.css work though.
Any thoughts on why the padding isn't being applied to my table?
So it turns out my stylesheet wasn't refreshing in the cache. I found an answer on this site.
I added these lines of code to my python (app-runner.py)
#app.context_processor
def override_url_for():
return dict(url_for=dated_url_for)
def dated_url_for(endpoint, **values):
if endpoint == 'static':
filename = values.get('filename', None)
if filename:
file_path = os.path.join(app.root_path,
endpoint, filename)
values['q'] = int(os.stat(file_path).st_mtime)
return url_for(endpoint, **values)
I use web.py Templator for my project and using the render('templates', base="") I combine a base layout with a page specific layout (simplified).
view.py
render = web.template.render('templates',base='layout')
return render.index()
shared layout file
layout.html
$def with (content)
<html>
<head>
<title>$content.title</title>
</head>
<body>
$:content
</body>
</html>
page specific template
index.html
$def with (values)
$var title: Hello Kitty
<p>Hello $values, how are you doin?</p>
The solution I'm looking for is how to achieve the following
login.html
$def with (values)
$var title: Enter credentials
<form>
<p><input type="text" name="user_name"></p>
<p><input type="password" name="user_pwd"></p>
<p><button type="submit">Open the gates</button></p>
</form>
$block_begin
<script>
// When the form is submitted, check the required fields and inform user
// if any data is missing or looks weird
</script>
$block_end
</body>
</html>
My question is, how do I add the script to the login.html template but not the index.html template? I'm not interested in having to add all JS logic to all pages, I would like to add this $block_begin/$block_end so that it appears at the bottom of the layout.html like this
layout.html
$def with (content)
<html>
<head>
<title>$content.title</title>
</head>
<body>
$:content
$block_begin
$block_end
</body>
</html>
The $block_begin/$block_end was just something I came up with to better explain myself.
Just to be clear, template -> defwith sections is a grammar, not an example. To use templates, check http://webpy.org/docs/0.3/templetor for examples.
At a high level, you create templates similar to
=== templates/index.html ===
$def with(values)
$var title: Hello Kitty
<p>Hello $values, how are you doin?</p>
=== templates/layout.html ===
$def with(content)
<html>
<head>
<title>$content.title</title>
</head>
<body>
$:content
</body>
</html>
Then in your python you render the template, passing in any parameters specified in the template. ("values" in this example.) The named template (index.html) is render using the base (layout.html), and as you've discovered, content contains the rendered internal bit (the results of index) and is inserted into the base template, layout.
You're asking how to get some script into login.html, but not in index.html & that's easy: just add the javascript code into the login.html template.
=== login.html ===
$def with (values)
$var title: Enter credentials
<form>
...
</form>
<script>
window.addEventListener('load', function () {
// whatever javascript you want to execute on load.
// If using jQuery, you'll have to use $$('form') or jQuery('form') rather
// than $('form'), as dollar signs are special within the template.
});
</script>
Something more clever? Use content more fully. Anything you define using $var in your template gets put into $content in the base layout.
If you want to include login.js only when your login.html page is rendered, you could simple create a new content attribute. In login.html:
$var extra_js: js/login.js
Then, in your layout file conditionally load the value at the bottom (where we like to load scripts).
=== templates/layout.html ===
...
<body>
$:content
$if content.get('extra_js', None):
<script type="text/javascript" src="$content.extra_js"></script>
</body>
</html>
You can make your layout.html more and more powerful, parameterizing meta data, scripts, css files, etc. Just like you did with $content.title, and let your individual template files drive different parts of the overall layout.
So during the following bottle server route everything works fine...
#route('/IFC/config/<policy>')
def config(policy):
if policy == "test":
html_nodes = ""
Nodes = IFC_main.get_nodes(ipaddr,username,password)
for node in Nodes:
html_nodes += '<li>'+node["name"]+'</li>'
return template("mgmt.tpl",html_nodes = html_nodes)
except when I look at the source code for the webpage that this produces it should be a dropdown menu with the values I provided but instead I get this...
<script language="JavaScript" type="text/javascript" src="/static/mgmt.js"> </script>
<link rel="stylesheet" type="text/css" href="/static/mgmt.css">
<body style = "background-color:#CCCCCA">
<img id="banner" style = "bg-color:CBCCCE" src="static/Cisco_emailHeader.png" alt="Banner Image"/>
<div style="width: 800px;height: 100px;position: absolute;top:0;bottom: 0;left: 0;right: 0;margin: auto;">
<h1>Management Connectivity</h1>
<ul class="dropdown-menu">
<li>calo2-leaf3</li><li>calo2- spine1</li><li>calo2-leaf2</li><li>calo2- leaf1</li><li>apic2</li><li>calo2- spine2</li><li>apic1</li><li>apic3</li>
</ul>
</div>
</body>
I understand I need to convert the string I'm passing into the template but I just haven't been able to figure out what. I'm assuming someone else has ran into this issue.
You can start the statement with an exclamation mark to disable escaping for that statement:
>>> template('Hello {{name}}!', name='<b>World</b>')
u'Hello <b>World</b>!'
>>> template('Hello {{!name}}!', name='<b>World</b>')
u'Hello <b>World</b>!'
You need to move the loop into template file,
% for node in nodes:
<li>{{ node.name }}</li>
% end
The code will change to,
#route('/IFC/config/<policy>')
def config(policy):
if policy == "test":
nodes = IFC_main.get_nodes(ipaddr,username,password)
return template("mgmt.tpl", nodes=nodes)
I'm trying to understand the Version One - Use Namespace.attr example for accessing descendant attributes in Mako. I have the base page template in page.html, and the index page in index.html which inherits page.html. I want to allow page.html (and page that inherits it) to specify their own Javascript and CSS files to include and allow page.html to handle rendering them.
page.html:
<!DOCTYPE html>
<%namespace name="common" file="common.html"/>
<%
# Scan for scripts and styles to include.
include_scripts = []
include_styles = []
for ns in context.namespaces.values():
if hasattr(ns.attr, 'include_scripts'):
include_scripts.extend(ns.attr.include_scripts)
if hasattr(ns.attr, 'include_styles'):
include_styles.extend(ns.attr.include_styles)
%>
<html>
<head>
<title>${self.attr.title}</title>
% for style in include_styles:
${common.style(style)}
% endfor
% for script in include_scripts:
${common.script(script)}
% endfor
</head>
<body>
${next.main()}
</body>
</html>
common.html:
<%def name="script(src)">
<script type="application/javascript" src="%{src | h}"></script>
</%def>
<%def name="style(href)">
<link rel="stylesheet" type="text/css" href="${href | h}"/>
</%def>
index.html:
<%inherit file="page.html"/>
<%!
# Set document title.
title = "My Index"
# Set document scripts to include.
include_scripts = ['index.js']
# Set document styles to include.
include_styles = ['index.css']
%>
<%def name="main()">
<h1>${title | h}</h1>
</%def>
This all renders the following page:
<!DOCTYPE html>
<html>
<head>
<title>My Index</title>
</head>
<body>
<h1>My Index</h1>
</body>
</html>
The rendered page is missing the styles and javascript includes that I'm expecting which should be:
<!DOCTYPE html>
<html>
<head>
<title>My Index</title>
<script type="application/javascript" src="index.js"></script>
<link rel="stylesheet" type="text/css" href="index.css"/>
</head>
<body>
<h1>My Index</h1>
</body>
</html>
In page.html, if I print context.namespaces I get:
{('page_html', u'common'): <mako.runtime.TemplateNamespace object at 0x1e7d110>}
Which indicates that only the imported common.html template is available and but no descendant template namespaces which inherit from page.html. How do I iterate through the inheriting template namespaces and check their attributes? I know I can use next to get the next template namespace, but how do I get the next template namespace after that if it exists?
The code snippet in page.html to check descendent templates for the include_scripts and include_styles attributes has to traverse next of each descendant template namespace to get to the next. Using context.namespaces only appears to list the local namespaces.
import mako.runtime
# Scan for scripts and styles to include.
include_scripts = []
include_styles = []
# Start at the first descendant template.
ns = next
while isinstance(ns, mako.runtime.Namespace):
if hasattr(ns.attr, 'include_scripts'):
include_scripts.extend(ns.attr.include_scripts)
if hasattr(ns.attr, 'include_styles'):
include_styles.extend(ns.attr.include_styles)
# NOTE: If the template namespace does not have *next* set, the built
# in python function *next()* gets returned.
ns = ns.context.get('next')
When using chameleon, I can replace element from a base template using the concept of slot. Where you define a slot and fill it using another tag. As there is no container element in head, how can one add elements to head ? :
The Layout file
<html>
<head>
<div metal:define-slot="extra_head"></div>
</head>
<body>
...
</body>
</html>
The content template that need to specify extra head.
<html metal:use-macro="load: main.pt">
<div metal:fill-slot="extra_head">
<script type="text/javascript" src="http://example/script.js"></script>
</div>
...
</html>
This gets rendered in :
<html>
<head>
<div metal:fill-slot="extra_head">
<script type="text/javascript" src="http://example/script.js"></script>
</div>
</head>
<body>
...
</body>
</html>
But there's no container tag in head so how can one define a slot to add stuff in the head ?
There's an alternative to using tal:omit-tag (which I'm finding annoyingly confusing - more than once I spent many minutes trying to figure out why a certain tag does not appear in the output when it's clearly present in the template, only to find tal:omit-tag neatly tucked in the far corner): if you use xml tags with tal: and metal: namespaces they won't appear in the output:
<html>
<head>
<metal:my-slot define-slot="extra_head"></metal:my-slot>
</head>
<body>
...
</body>
</html>
and in the child template:
<metal:template use-macro="load: main.pt">
<metal:any-descriptive-name fill-slot="extra_head">
<script type="text/javascript" src="http://example/script.js"></script>
</metal:any-descriptive-name>
...
</metal:template>
Note how the template becomes much more readable and self-descriptive and does not contain weird things such as a <div> inside <head> :)
You also can omit tal: and metal: prefixes on attributes when using namespaced tags, so
<h1 tal:condition="..." tal:content="..." tal:omit-tag="">Hi there! Bogus content for added confusion!</h1>
becomes
<tal:greeting condition="..." content="..." />
To remove the tag one has to use tal:omit-tag :
In the content template, use :
<html metal:use-macro="load: main.pt">
<div metal:fill-slot="extra_head" tal:omit-tag="">
<script type="text/javascript" src="http://example/script.js"></script>
</div>
...
</html>
The div is not part of the result. Read the doc.