2017-04-19 7 views
0

私はviews.pyでロードしたtxtファイルを持っています(今は段落で分割していますが、後でもっとうまくいくでしょう)。Djangoで解析する前にテンプレートとテンプレート変数をあらかじめロードしています

この文書の中で、私はDjangoのテンプレートタグ{{user.firstName}}などのいくつかの

私はそのHTMLを追加取得するには、テンプレートにこの文書を送る、などを持っている。しかし、それは表示されませんタグ。私は、Djangoがテンプレートを一度ロードして、それをすべてツリーの中に保存することを知っています。私は回避策を見つけることができません。文書をあらかじめロードしてからパーサを実行させることはできますか? HTMLタグをview.pyに追加して解析する前にテンプレートに送ることができますか?

どのようなアイデアや考えがすばらしいですか。ここで

は、私はコードを持っているものです。

View.py

class DocumentReview(TemplateView): 
template_name = 'paperwork\document.html' 

def get_context_data(self, **kwargs): 
    context = super(DocumentReview, self).get_context_data(**kwargs) 
    context['user'] = {'firstName': 'x', 'lastName': 'y'} 
    context['document'] = self.get_document() 
    return context 


def get_document(self): 
    module_dir = os.path.dirname(__file__) # get current directory 
    file_path = os.path.join(module_dir, 'documents\sample.txt') 
    document = {} 
    with open(file_path, 'r') as fp: 
     data = fp.read() 
     document = data.split("\n\n") 
    return document 

ここにsample.txtです:

Hello {{ user.firstName }} {{ user.lastName }}, 

This is a sample txt file. 

そして、これがdocument.html

 {% for para in document %} 
       <p>{{ para }}</p> 
       {% endfor %} 
です

答えて

1

thを使用する必要があります電子template loaderモジュール、およびあなたのget_document機能変更:

from django.template.loader import render_to_string 
def get_document(self, context): 
    data = render_to_string('documents\sample.txt', context) 
    return data.split("\n\n") 

をそして、あなたはこのようにそれを呼び出します。その前に

context['document'] = self.get_document(context) 

、あなたのファイルを見つけるローダーのために、あなたのsettings.TEMPLATESを変更する必要がありdocuments\sample.txt

関連する問題