2013-10-01 4 views
5

सर्वर में मैं एक तर्क के साथ एक टेम्पलेट प्रस्तुत करना, इस तरह:टॉरनाडो से js फ़ाइल में तर्क कैसे पास करें लेकिन HTML नहीं?

self.render('templates/test.html', names="['Jane', 'Tom']") 

और मैं सफलतापूर्वक इस से test.html की <script> में यह मिल गया:

var N = "{{ names }}"; 

अब मैं js code अलग करना चाहते हैं और html:

<script type="text/javascript" src="static/test.js"></script> 

लेकिन यह विफल रहा है जब मैंडालउस जेएस फ़ाइल में।

क्या कोई मुझे बता सकता है कि इसके साथ क्या करना है? धन्यवाद !

उत्तर

7

आप सेटर समारोह बना सकते हैं तर्क के लिए HTML फ़ाइल से कहा जा पारित कर दिया:

$ tree 
. 
├── static 
│   └── scripts 
│    └── test.js 
├── templates 
│   └── index.html 
└── test.py 

तूफान कोड:

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import os.path 
import tornado.httpserver 
import tornado.ioloop 
import tornado.options 
import tornado.web 

from tornado.options import define, options 
define("port", default=8000, help="run on the given port", type=int) 

class IndexHandler(tornado.web.RequestHandler): 
    def get(self): 
     self.render('index.html', test="Hello, world!") 

if __name__ == '__main__': 
    tornado.options.parse_command_line() 
    app = tornado.web.Application(handlers=[ 
     (r'/', IndexHandler)], 
     static_path=os.path.join(os.path.dirname(__file__), "static"), 
     template_path=os.path.join(os.path.dirname(__file__), "templates")) 
    http_server = tornado.httpserver.HTTPServer(app) 
    http_server.listen(options.port) 
    tornado.ioloop.IOLoop.instance().start() 

टेम्पलेट:

<!DOCTYPE html> 
<html> 
<head> 
    <title>Test</title> 
    <script src="{{ static_url('scripts/test.js') }}" type="application/javascript"></script> 
</head> 
<body> 
    <input type="button" onclick="show_test()" value="alert" /> 
    <script type="application/javascript"> 
     set_test("{{test}}"); 
    </script> 
</body> 
</html> 

JavaScript फ़ाइल:

/* test.js */ 
var test = "" 

function set_test(val) 
{ 
    test=val 
} 

function show_test() 
{ 
    alert(test); 
} 
+0

अच्छा विचार। धन्यवाद ! – yakiang

संबंधित मुद्दे