2013-09-23 52 views
1

我是新的谷歌應用程序引擎和python開發,並試圖使用Jinja2作爲我的模板引擎。我有一個頁面,我試圖「包括」頁眉和頁腳,我不斷收到此錯誤:TemplateNotFound:base/header.htmlPython谷歌應用程序引擎Jinja2找不到包括

我的代碼如下。如果您有任何建議,請告訴我。

的Python

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), 
    extensions=['jinja2.ext.autoescape']) 

class MainPage(webapp.RequestHandler): 


    def get(self): 
     template_values = {'title' : 'Test Value'} 
     template = JINJA_ENVIRONMENT.get_template('/public/templates/index.html') 
     self.response.write(template.render(template_values)) 

配置

libraries: 
- name: webapp2 
    version: latest 
- name: jinja2 
    version: latest 

文件結構

- my application 
    - public 
    - scripts 
    - stylesheets 
    - templates 
     - base 
     - header.html 
     - footer.html 
     - index.html 
    - app.yaml 
    - myapplication.py 

HTML(的index.html)

{% include "base/header.html" %} 
<nav class="top-bar" style=""> 
    <!-- more html here --> 
</nav> 
{% include "base/footer.html" %} 

回答

0

我沒有用裝載機屬性Jinja2的,所以我不知道這行做什麼

loader=jinja2.FileSystemLoader(os.path.dirname(__file__)) 

但我確實有成功的Jinja2使用App Engine等等我想我可以幫忙。我知道默認情況下,jinja2會在您的項目根目錄中查找名爲「templates」的目錄。因此,對於header.html,jinja2會希望該文件位於「templates/base/header.html」中。

如果您在environment.py在get_template功能是Jinja2的看,如果拋出一個

If the template does not exist a :exc:`TemplateNotFound` exception is 
    raised. 

在您的應用程序引擎項目的根目錄下創建一個模板目錄,並將所有的Jinja2模板到那裏,讓我知道如果修復它。當您通過模板名稱的Jinja2他們都將是相對於文件夾,以便調用看起來應該像

template = JINJA_ENVIRONMENT.get_template('index.html') 

與/templates/index.html的index.html是在你的根。

如果是這樣,我可以告訴你如何通過將字典傳遞給它來自定義jinja2默認配置。

+0

如果這不起作用,請告訴我。我將通過應用引擎和jinja2提供我的設置配置的完整示例。 –

+0

非常感謝您的幫助!根據您的建議,我認爲我會更接近。我現在將loader屬性更改爲: loader = jinja2.FileSystemLoader('templates /','templates/base /')並將模板移動到根目錄。我現在收到一個新錯誤:文件「/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/jinja2-2.6/jinja2/loaders.py」,第169行, get_source contents = f.read()。decode(self.encoding) LookupError:unknown encoding:templates/base/ 這些文件的編碼是UTF-8。 – Jon

+0

這個錯誤是因爲jinja2.FileSystemLoader('templates /','templates/base /')中的第二個參數。如果您查看loaders.py的源代碼,那麼構造函數將接受編碼參數作爲第二個參數。所以你說的編碼是'tempaltes/base'。我認爲你應該刪除它並保留jinja2.FileSystemLoader('模板')。然後在base中引用您的模板爲'base/mytemplate.html'。讓我知道那是怎麼回事。如果你想,如果我們不能讓你的工作,我仍然會提供我的設置。 –

相關問題