2010-11-30 139 views
0

我正在使用AppEngine和webapp框架(python)。在我的劇本,我動態生成的JavaScript代碼使用Django,例如:包含帶有模板的javascript文件

蟒蛇控制器文件

template_values = { 
    'page': '1',    
} 

path = os.path.join(os.path.dirname(__file__), "../views/index.html") 
self.response.out.write(template.render(path, template_values)) 

index.html文件

<html> 
<head> 
... 
<script> 
{% if page %} 
    alert("test"); 
{% endif %} 
</script> 
</head> 
<body> 

... 
</body> 
</html> 

現在,而不是使用內聯<script>標籤我想使用<link>標籤來引用包含腳本的JS文件。但是,我不明白我可以使用模板引擎來做到這一點。如果我包含一個JS文件(動態),它會以某種方式知道「頁面」的值,但「page」僅在index.html的範圍內是已知的。

任何想法?

感謝,

喬爾

回答

0

如果你想動態生成HTML的JavaScript代碼, 您可以編寫Python代碼中的代碼

page = 0 
template_values = { 
    'js_code': 'alert("test:'+str(page)+'")',    
} 
path = os.path.join(os.path.dirname(__file__), "../views/index.html") 
self.response.out.write(template.render(path, template_values)) 
index.html中

<script> 
{{js_code}} 
</script> 

如果你想生成一個js

動態文件,你可以嘗試假裝有一個js文件,並且生成它的內容 。

class JSHandler(BaseHandler): 
    def get(self): 
     page= str(self.request.get("page")) 
     js_code ='alert("page:'+page+'");' 
     self.response.out.write(js_code) 


def main(): 
application = webapp.WSGIApplication([ 
    ('/code.js', JSHandler), 
    ], debug=True) 
wsgiref.handlers.CGIHandler().run(application) 

然後你就可以在你的HTML

<script type="text/javascript" src="/code.js?page={{page}}">></script> 
0

您可能是過於複雜的簡單情況,或者你還沒有解釋清楚你的問題。

如果要包含位於外部的JavaScript文件,您可以使用<script>標記,而不是<link>

如果你有這樣的模板代碼:

<html> 
<head> 
{% if page %} 
    <script type="text/javascript" src="/js/foo.js"></script> 
{% endif %} 
</head> 
... 
</html> 

page不是None,模板將呈現以下HTML瀏覽器:

<html> 
<head> 
    <script type="text/javascript" src="/js/foo.js"></script> 
</head> 
... 
</html> 

,瀏覽器將嘗試加載由<script>標記指向的資源。瀏覽器不知道該標籤如何進入它加載的HTML。

+0

從示例代碼編寫代碼很顯然,用戶想向一個JavaScript文件中的模板代碼。 – rutherford 2012-10-25 12:29:16

相關問題