2017-04-20 75 views
0

我想創建一個模板繼承使用像url_for方法的另一個。如果我刪除import聲明我得到一個錯誤:馬科避免python進口

TypeError 
TypeError: 'Undefined' object is not callable 

才能擺脫低於進口的?

main.html中的文件:

<!doctype html> 
<%! 
    from flask.helpers import url_for 
    from flask.globals import request 
%> 
<html lang=en> 

<head> 
    <%block name="additional_scripts"/> 
</head> 
<body> 

</body> 
<h1>Presence analyzer</h1> 
    <ul> 
     % for key, template in templates.items(): 
      <li 
       % if request.path == '/statistics/{}/'.format(template['name']): 
        id="selected" 
       % endif 
      > 
       <a href="${url_for('statistics_view', chosen=template['name'])}">${template['description']}</a> 
      </li> 
     % endfor 
    </ul> 
</html> 

的繼承的文件:

<%inherit file="main.html"/> 

<%! 
    from flask.helpers import url_for 
%> 

<%block name="additional_scripts"> 
    <script type="text/javascript"> 
     google.load("visualization", "1", {packages:["corechart", "timeline"], 'language': 'pl'}); 
    </script> 
    <script src="${url_for('static', filename='js/presence_weekday.js')}"></script> 
</%block> 

調用視圖的方法:

@app.route('/statistics/<chosen>/') 
def statistics_view(chosen): 
    try: 
     return LOOKUP.get_template(templates[chosen]['template']).render(templates=templates) 
    except KeyError: 
     abort(404) 

而且main.py文件在其中創建的應用程序:

import os 

from flask import Flask 
from mako.lookup import TemplateLookup 

app = Flask(__name__) # pylint: disable=invalid-name 
LOOKUP = TemplateLookup(directories=[os.path.join(os.path.dirname(os.path.realpath(__file__)), 
                'templates')]) 

回答

0

我發現了另一種方法來做到這一點。問題在於我呈現模板的方式。

首先,我需要在main.py文件創建MakoTemplates例如,通過加入這一行,並刪除LOOKUP

MakoTemplates(app) 

然後,而不是使用LOOKUP.get_template...我回:

return render_template(templates[chosen]['template'], templates=templates) 

這讓我刪除這些標籤。

0

無法避免導入,<%! %>叫做Module-level Blocks,當模板加載到內存時它將被執行一次。但它不能在模板之間共享。就像Python模塊的工作方式一樣,所有東西都需要在使用前明確導入。