16👍
You want a context processor. The data they generate is included in every context created as a RequestContext
. They are perfect for this.
Combined with base templates that show common things, you can get rid of lots of need for copying and pasting code.
3👍
use inheritance in the templating engine:
have a base.html that includes the common code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<title>{% block title %}My amazing site{% endblock %}</title>
</head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
then in each page that needs that common code, simply:
{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
http://docs.djangoproject.com/en/dev/topics/templates/#id1
this combined with context processessing will eliminate a lot of duplicate code.
- [Django]-Using Python Dataclass in Django Models
- [Django]-Is there a better way to check if the values of an AJAX request are valid?
- [Django]-Collectstatic command excluding nested directories and files
- [Django]-How to Show and hide form fields based on a selection from a dropdown menu in Django
- [Django]-Django 1.6 + RabbitMQ 3.2.3 + Celery 3.1.9 – why does my celery worker die with: WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV)
- [Django]-Schemamigration/refactor model using south
- [Django]-.Stay on SSL across redirects
- [Django]-Python Webshop for Retailers / Distributors
- [Django]-How to deal with unstable data received from RFID reader?
0👍
To do exactly what you request, I’d simply define a function:
def foobar(req):
return render_to_response(
"core/index.html",
{
"locality": getCityForm(req.user),
},
context_instance=RequestContext(req)
)
put it in some module myfun
, and return myfun.foobar(request)
wherever needed. You’re likely to want a few more arguments, but as long as it stays about this simple, it’s simpler that defining middleware, using OOP, &c.
- [Django]-Django – Establishing Many To Many Relationship Between 2 Models Without Through Table Using Formsets
- [Django]-Django RuntimeError: maximum recursion depth exceeded