2011-01-29 60 views
0

我想向我的基本模板添加一個隨機口號。我意識到簡單的方法來做到這一點是有一個數據庫表與我的口號,得到一個隨機的,並將其傳遞給模板。django模板從包含文件中獲取隨機行的最佳方式

問題是,如何在不使用數據庫的情況下執行此操作?在我的基本模板中,我想包含一個帶有一串口號的文件,每行一個,並且模板會隨機選擇一個。我知道random過濾器會從列表中選取一個隨機值,所以不知何故,我需要include這個口號文件,但是作爲一個列表。

+0

爲什麼要在數據庫中使用平面文件有特別的原因嗎? – KyleWpppd 2011-01-30 08:26:49

+0

口號很少會改變,只有少數人會改口號。即使使用數據庫緩存,爲了在每個頁面標題上放置一個句子,創建和維護一個單獨的應用程序(或「骯髒」一個不相關的現有應用程序)似乎是一個不必要的複雜。對我來說,邏輯位置應該放在我的`base.tml`模板中。 – gorus 2011-01-30 19:26:25

+0

我的想法是,如果有一個函數隨機選擇一個口號,那麼數據庫處理它比使用平面文件更有效率。我知道調用db可以被緩存,但是可以調用你的口號嗎? – KyleWpppd 2011-01-30 23:24:58

回答

0

兩個選項我看到:

1)使用一個上下文處理器加載該隨機引用(即從平面文件),然後插入到上下文。例如:

# 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)創建一個自定義模板標籤,你從一個平面文件加載報價等:http://docs.djangoproject.com/en/dev/howto/custom-template-tags/

+0

謝謝!對於(1):由於我想在我的`header.inc`中包含口號,因此希望避免包含一個額外的變量,因爲我有不同的視圖傳遞不同的上下文,使得這條路線變得複雜。對於(2):請參閱我對Loarfatron的回覆 - 如果沒有更好的方法,我想這是一條路。 – gorus 2011-01-30 19:52:06

0

我會投票給一個模板標籤。將隨機引號存儲在文本文件中,並在單獨一行中添加每個引號。然後在模板標籤中隨機讀一行,這裏有一個很好的解釋: http://www.regexprn.com/2008/11/read-random-line-in-large-file-in.html。 轉載如下:

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 

最後返回行,以便您的模板標籤可以把它打印出來。

相關問題