Optimal way for django template to get random line from included file
I want to add a random slogan to my base template. I realize the easy way to do this is to have a db table with my slogans, get a random one, and pass it to the template.
The question is, how do I do it without using the db? In my base template, I want to include a file with a bunch of slogans, one on each line, and have the template randomly pick one. I know the random
filter will pick a random value from a list, so somehow,开发者_如何学编程 I need to include
the slogan file, but as a list.
Two options I see:
1) Use a context-processor to load this random quote (i.e. from a flat file), then insert into context. Example:
# create your own context-processor file (myutils/context_processors.py)
def my_random_quote_processor(request):
context = {}
# generate your string you want in template
# ....
context['RANDOM_QUOTE'] = my_random_quote
return context
# in settings.py, tell django to include your processor
TEMPLATE_CONTEXT_PROCESSORS = (
# ...,
'myutils.context_processors.my_random_quote_processor'
)
# in your base template, just include the template var
<p>quote: {{ RANDOM_QUOTE }}</p>
# make sure in your views, you set the context_instance
def my_view(request):
# ...
return render_to_response('myapp/mytemplate.html', c,
context_instance=RequestContext(request))
2) Create a custom template-tag where you load the quote from a flat file, etc.: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
I would vote for a template tag. Store the random quote in a text file with each quote on a separate line. Then in the template tag read in a line at random, a nice explanation of how to do that here: http://www.regexprn.com/2008/11/read-random-line-in-large-file-in.html. Reproduced below:
import os,random filename="averylargefile" file = open(filename,'r') #Get the total file size file_size = os.stat(filename)[6] while 1: #Seek to a place in the file which is a random distance away #Mod by file size so that it wraps around to the beginning file.seek((file.tell()+random.randint(0,file_size-1))%file_size) #dont use the first readline since it may fall in the middle of a line file.readline() #this will return the next (complete) line from the file line = file.readline() #here is your random line in the file print line
Finally return the line so your template tag can print it out.
If your slogans base is pretty small you can use pickle module. And operate your base like a normal list. http://docs.python.org/library/pickle.html
But i think the best solution is to keep your slogans database in real db
Just found out this snippet: http://djangosnippets.org/snippets/2121/ will solve it.
精彩评论