如何将python变量传递给html变量?
我需要从python中的文本文件中读取url链接作为变量,并在html中使用它。文本文件“ file.txt”仅包含一行“
http://188.xxx.xxx.xx:8878 ”,此行应保存在变量“
link”中,然后在其中使用此变量的包含html,以便当我单击按钮图像“
go_online.png”时应打开链接。我尝试按照以下方式更改代码,但无法正常工作!有什么帮助吗?
#!/usr/bin/python
import cherrypy
import os.path
from auth import AuthController, require, member_of, name_is
class Server(object):
_cp_config = {
'tools.sessions.on': True,
'tools.auth.on': True
}
auth = AuthController()
@cherrypy.expose
@require()
def index(self):
f = open ("file.txt","r")
link = f.read()
print link
f.close()
html = """
<html>
<script language="javascript" type="text/javascript">
var var_link = '{{ link }}';
</script>
<body>
<p>{htmlText}
<p>
<a href={{ var_link }} ><img src="images/go_online.png"></a>
</body>
</html>
"""
myText = ''
myText = "Hellow World"
return html.format(htmlText=myText)
index.exposed = True
#configuration
conf = {
'global' : {
'server.socket_host': '0.0.0.0', #0.0.0.0 or specific IP
'server.socket_port': 8085 #server port
},
'/images': { #images served as static files
'tools.staticdir.on': True,
'tools.staticdir.dir': os.path.abspath('/home/ubuntu/webserver/images')
}
}
cherrypy.quickstart(Server(), config=conf)
-
首先,不确定javascript部分是否有意义,就将其省略。另外,打开 p
标签但不关闭它。不知道您的模板引擎是什么,但是您可以只使用纯python传入变量。另外,请确保在链接周围加上引号。因此,您的代码应类似于:class Server(object): _cp_config = { 'tools.sessions.on': True, 'tools.auth.on': True } auth = AuthController() @cherrypy.expose @require() def index(self): f = open ("file.txt","r") link = f.read() f.close() myText = "Hello World" html = """ <html> <body> <p>%s</p> <a href="%s" ><img src="images/go_online.png"></a> </body> </html> """ %(myText, link) return html index.exposed = True
(顺便说一句,%s是字符串占位符,它将在多行字符串的末尾填充%(firstString,secondString)中的变量。