I have a website build via Statik (a static web site generator, build with python).
Now I'd like to build a navigation out from my existing data or views, via a property like e.g. show_in_navigation = Boolean.
I thought about writing a custom template tag to get a list of all instances with show_in_navigation = True - but I don't know where to start or what would be the best approach in the first place;-)
My goal is a Twitter Bootstrap navbar-nav component filled with my show_in_navigation entries (with a bonus for highlighting the current page).
Any hints or tips?
My current implementation defines a navigation_bar variable in the main configuration:
# config.yml
context:
static:
navigation_bar: [['home', 'Home'], ['about', 'About'], ['contact', 'Contact']]
# templates/includes/navigation.html
<ul>
{% for pk, title in navigation_bar %}
<li {% if pk == active_page %} class="active"{% endif %}>
{{ title }}
</li>
{% endfor %}
</ul>
# templates/about.html
{% extends "base.html" %}
{% set active_page = "about" %}
... but that seems to be very verbose and not dry (e.g. repeating site titles, setting the active page)...
Related
I just worked through the flask tutorial, step by step creating a blog web application. The entries are rendered via a jinja template:
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
{% else %}
<li><em>Unbelievable. No entries here so far</em>
{% endfor %}
</ul>
The color is defined in a style.css:
a, h1, h2 { color: #377ba8; }
However, I really would like to be able, to switch the color of the entry depending on a condition. For example, if the entry.text is 'apples', it should be red, otherwise green.
Being a bloody noob to web development, I feel like something like this might be javascript, but I simply don't see how to accomplish this task and would appreciate your help.
Best,
gbrown
First of all, you should add a rule to your CSS so that you can change the color by applying a class to your element. Something like this:
.apples {
color: red;
}
Then, you need to make your Jinja template apply a class attribute depending on the value of entry.text:
<ul class="entries">
{% for entry in entries %}
<li {% if entry.text == 'apples' %} class="apples" {% endif %}>
<h2>{{ entry.title }}</h2>
{{ entry.text|safe }}
</li>
{% else %}
<li>
<em>Unbelievable. No entries here so far.</em>
</li>
{% endfor %}
</ul>
This technique is described in the Jinja manual for example under the topic “Highlighting Active Menu Items”.
I am making kind of dynamic menu. when you click menu on the top, it show sub menu on the left side. I searched with keyword 'dynamic menu' from stackoverflow and google. I got idea to build that kind of menu. I made it like below.
1) render data(menu list) in context to template by custom context processor.
2) using custom template tag which is provided by django-mptt package.
3) show top menu in base template.
4) move to another template to show sub menu according to what top menu you click
I made custom context_processor to use menu in context in every template.
context_processor.py
from manager.models import Menu
def menu(request):
menu_list = list(Menu.objects.all())
return {'menu':menu_list}
template.py(example)
{% load mptt_tags %}
<nav id="{{ menu_id }}" class="tree-menu">
<ul>
{% recursetree menu %}
<li class="menu
{% if node.is_root_node %}root{% endif %}
{% if node.is_child_node %}child{% endif %}
{% if node.is_leaf_node %}leaf{% endif %}
{% if current_menu in node.get_descendants %}open{% else %}closed{% endif %}
">
{{ node.menu_name }}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
{% if node.items and node.items.exists %}
<ul class="items">
{% for item in node.items.all %}
{% if item_template %}
{% include item_template %}
{% else %}
{% include "menu/tree-item.html" %}
{% endif %}
{% endfor %}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
</nav>
mptt_tags.py
#register.tag
def recursetree(parser, token):
"""
Iterates over the nodes in the tree, and renders the contained block for each node.
This tag will recursively render children into the template variable {{ children }}.
Only one database query is required (children are cached for the whole tree)
Usage:
<ul>
{% recursetree nodes %}
<li>
{{ node.name }}
{% if not node.is_leaf_node %}
<ul>
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
"""
bits = token.contents.split()
if len(bits) != 2:
raise template.TemplateSyntaxError(_('%s tag requires a queryset') % bits[0])
queryset_var = template.Variable(bits[1])
template_nodes = parser.parse(('endrecursetree',))
parser.delete_first_token()
return RecurseTreeNode(template_nodes, queryset_var)
My Question
If you see django manual about QuerySet, it says that "Each QuerySet contains a cache to minimize database access". It is obvious that, if you query same data in certain rule, it doesn't seem hit database again but return result from cache. Then I am querying Menu.objects.all() in custom context processor. This result(menu_list = Menu.objects.all()) will be in context every time, you can use menu data on every template repeately. So does it reuse the result from cache without hitting database again?
If menu_list = Menu.objects.all() in custom context processor hit database every time whenever template load this menu list, Does it work in this way to reuse menu data from cache without hitting database everytime?
context_processors.py
from manager.models import Menu
from django.core.cache import cache
def menu(request):
menu_list = cache.get_or_set('menu_list', list(Menu.objects.all()))
return {'menu':menu_list, 'redis':"Food"}
Lastly, I don't know if there are many people using django-mptt package. I guess just a few people have experience using it in person. It says "Only one database query is required (children are cached for the whole tree)" so does it mean if I use django-mptt package and get menu from it on template, it automatically cache its data?
Well, I am not clear about django cache system.
It would be really appreciate if you can give me answer and insight for my questions. Thanks for reading!
When I blog, I like to separate each blog-post into its own .html file (is that ok?)
This prevents the file getting too big, and makes it easy to go back and edit a previously written blog post if need be.
Occasionally the blog post will contain css/js/ajax/template variables.
But on my website, I like all the blog posts on one page (so I can scroll through them all, instead of going to a separate page for each post)
Here is an html file that contains two blog posts:
{% extends "base.html" %}
{% block blog_posts %}
<!-- links/targest for the side menu to jump to a post -->
<li>Post2 - April 2012</li>
<li>Post1 - Feb 2012</li>
{% endblock %}
{% block content %}
<div id="post1">
spam1 blah blah
</div>
<div id="post2">
spam2
</div>
{% endblock %}
and in base.html I have something like:
<div id="content-container">
<div id="section-navigation">
<ul>
{% block blog_posts %}
{% endblock %}
</ul>
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</div>
What is the best way for me to split these blog posts out into separate files using webapp2 and jinja2?
e.g. blog1.html might look like:
{% block blog_posts %}
<!-- links/targest for the side menu to jump to a post -->
<li>Post1 - Feb 2012</li>
{% endblock %}
{% block content %}
<div id="post1">
spam1 blah blah
</div>
{% endblock %}
(And I would want the links and the blogposts to be displayed in the right order on the website)
I could think of a way of doing it where post2 extends post1.html, post3 extends post2.html etc, but I would prefer to fan out more
"Henry and Kafura introduced Software Structure Metrics Based on Information Flow in 1981[2] which measures complexity as a function of fan in and fan out."
Thanks
#robert king, your design has data embedded directly in the template. Templates should only contain the blueprint to a view, and they should be rendered with new data generated from your main code every time. I simulate this process here (Edited to illustrate the use of a loop to extract post titles, and the display of a single post.):
import jinja2
# NOTE: in this template there is no data relating to specific posts.
# There are only references to data structures passed in from your main code
page_template = jinja2.Template('''
<!-- this is a navigation block that should probably be in base.html -->
{% block blog_posts %}
<!-- links/targets for the side menu to jump to a post -->
{% for post in posts %}
<li><a href="{{ post.url }}">{{ post.title }}
- {{ post.date }}</a></li>
{% endfor %}
{% endblock %}
<!-- this is a content block that should probably be in page.html -->
{% block content %}
<div id="post">
<h1>{{ current.title }}</h1>
<h2>{{ current.date }}</h2>
<p>{{ current.content }}</p>
</div>
{% endblock %}
''')
# NOTE your main code would create a data structure such as this
# list of dictionaries ready to pass in to your template
list_of_posts = [
{ 'url' : '#post1',
'title' : 'My first post',
'date' : 'Feb 2012',
'content' : 'My first post is about Hello World.'},
{ 'url' : '#post2',
'title' : 'My second post',
'date' : 'Apr 2012',
'content' : 'My second post is about Foo Bar.'}
]
# Pass in a full list of posts and a variable containing the last
# post in the list, assumed to be the most recent.
print page_template.render(posts = list_of_posts,
current = list_of_posts[-1])
Hope this helps.
EDIT See also my answer to a question on "Site fragments - composite views"
I just found another option in the jinja2 tutorial. I think it makes more sense for my handler to pass my template a list of filenames of blog posts, and then to include the blog posts.
include - returns the rendered contents of that file into the current namespace:
{% include 'header.html' %}
<div ...
{% include 'footer.html' %}
Included templates have access to the variables of the active context by default. For more details about context behavior of imports and includes see Import Context Behavior.
From Jinja 2.2 onwards you can mark an include with ignore missing in which case Jinja will ignore the statement if the template to be ignored does not exist. When combined with with or without context it has to be placed before the context visibility statement. Here some valid examples:
{% include "sidebar.html" ignore missing %}
{% include "sidebar.html" ignore missing with context %}
{% include "sidebar.html" ignore missing without context %}
New in version 2.2.
You can also provide a list of templates that are checked for existence before inclusion. The first template that exists will be included. If ignore missing is given, it will fall back to rendering nothing if none of the templates exist, otherwise it will raise an exception. Example:
{% include ['page_detailed.html', 'page.html'] %}
{% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}
When I read the raw html file (file.read()) and passed the data to my template, it escaped all the html.
instead of {{data}} i had to use {{data|safe}} which allowed raw html.
something like:
class HomeHandler(BaseHandler):
def get(self):
file_names = sorted(os.listdir('blog_posts'))
html = [open('blog_posts/%s' % fn).read() for fn in file_names]
templates = {'html': enumerate(html)}
self.render_template('home.html', **templates)
{% block content %}
{% for num,data in html %}
<div id="post{{num}}">
{{data|safe}}
</div>
<br />
<img src="http://www.sadmuffin.net/screamcute/graphics/graphics-page-divider/page-divider-007.gif" border=0>
<br />
{% endfor %}
{% endblock %}
(make sure the directory isn't a static directory)
I am trying to highlight a link of a currently opened category tab, here is what i have already done:
globs.py
def globs(request):
cats = Category.objects.all()
return {'cats': cats}
views.py
def news_by_category(request, slug):
c = Category.objects.get(slug=slug)
news = News.objects.filter(category=c, status='p').order_by('-id')
#news = c.news_set.all().order_by('-id')
return object_list(
request,
news,
paginate_by = 5,
extra_context = {'c':c},
template_name = 'news_by_category.html')
base.html #bodyclass
<body class="{% block bodyclass %}{% endblock %}">
news_by_category.html
{% block bodyclass %}{{c|cut:" "}}{% endblock %}
base.html
<li><h4>Categories:</h4></li>
{% for i in cats %}
<li class="{{i.name|safe|cut:" "}}_li">
{{ i.name }}
</li> {% endfor %}
What i need to do now is to create style for every category, in category list, I could achieve this easily by styling inside a html file, but I'm not sure wether that would be proper (Would it?). I came up with some css styling,
{% for i in cats %}
body.{{ i|safe|cut:" "}} li.{{i|safe|cut:" "}}_li {
color: red;
}
but as I can't use django template tags inside my .css file, this wont work.
My questions:
1) How could i make this css file work for me. Any chance for a little step by step?
2) If I failed step1, how improper would it be to style those few li elements inside html file?
EDIT: /trying another way
I tried using:
base.html
{% for i in cats %}
<li class="{% ifequal 'request.get_full_path' '/k/{{ i.slug }}/' %}active{% endifequal %}">
{{ i.name }}
</li> {% endfor %}
.css
.active {{color:red;}
When i compared {{ request.get_full_path }} and /k/{{i.slug}}/ both returned same thing... but if its inside ifequal it doesnt seem to work.
You can create a simple class named "active" or something along those lines and add it to the current tab. Then, in your CSS you apply the active styles to that class. So you just append the active class and it'll automatically take the active style.
If you have a url:
{% url app:home i.slug as home %}
<li {% ifequal request.get_full_path home %}class="active"{% endifequal %}>
I'm trying to access session keys within a loop that needs to be dynamic, I think you'll get what I'm going for by looking at my code that isn't working.
{% for q in questions %}
<div class="question_wrap">
<h2>{{ q }}</h2>
# this does not work
{% if not request.session.get(str(q.id), False) %}
<!-- show them vote options -->
{% else %}
<!-- dont show options -->
{% endif %}
</div>
{% endfor %}
The syntax of Django templates is very limiting in order to prevent people from putting too much logic inside templates and doesn't allow you to pass parameters to methods.
You can prepare a list of tuples already in the view or write a simple template tag for that. The first options is usually easier:
In the view:
questions = [(q, request.session.get(str(q.id), False)) for q in questions]
In the template:
{% for q, has_voted in questions %}
...
{% endfor %}