Login

Add URL Segments to Templates

Author:
epicserve
Posted:
October 1, 2008
Language:
Python
Version:
1.0
Tags:
template url path segment
Score:
-1 (after 5 ratings)

Add this code to you your context_processors.py in your project and then install it in your settings.py TEMPLATE_CONTEXT_PROCESSORS. In your template you can print out a segment of a url by using {{ segment_1 }}. For example if you're on the page "/mysite/section1/section2/" and you used {{ segment_2 }} it would print section1.

This idea was taken from Expression Engines URL Segments, http://expressionengine.com/docs/templates/globals/url_segments.html.

This comes in handy if you only want to do something in your template if the page your on has a particular segment.

FYI, I haven't used this in a production setting yet so it could be buggy still.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def url_segments(request):

	from urlparse import urlparse
	
	# convert the url path into a list	
	url_segment = request.path_info.strip("/").split("/")
	
	# assign each segment to it's on var
	url_segment_dict = {}
	for i in range(len(url_segment)):
		url_segment_dict["segment_%d" % (i+1)] = url_segment[i]
	
	return url_segment_dict

More like this

  1. template tag for highlighting currently active page by adunar 6 years, 9 months ago
  2. FormWizard inside view with proper context handling and site templating support, without having to use urls.py by sleepycal 5 years, 7 months ago
  3. Default Template Loading by nirvdrum 8 years ago
  4. Django csrf_token Template Tag Fix by Reustle 4 years, 12 months ago
  5. Add GET parameter tag by marltu 5 years ago

Comments

Please login first before commenting.