如何将Python变量传递给HTML变量?

4 投票
1 回答
31632 浏览
提问于 2025-04-17 17:26

我需要在Python中从文本文件读取一个网址链接,并把它当作变量使用,然后在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)

1 个回答

4

首先,不太确定你写的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)中的变量来填充。

撰写回答