Login

Add URL Segments to Templates

Author:
epicserve
Posted:
October 1, 2008
Language:
Python
Version:
1.0
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 - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 3 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.