python - 如何将python变量传递给html变量?

标签 python html variables webserver readfile

我需要从 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) 中的变量。

关于python - 如何将python变量传递给html变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15137520/

相关文章:

python - 如何组合多个 NumPy bool 数组?

jquery - 如何使文本 float 在图像 html css 之上

c# - 如何避免重复将大量名称相似的变量分配给许多对象中的大量字段

python - 回溯仅显示多行命令的一行

python - 如何从字典键列表中提取特定项目

javascript - 在php for循环中回显带有图像的文本

Python:如何在另一个函数中使用一个函数中的变量

bash - 在文件名中使用计数变量

python - 用python画地形?

html - 如何使带引号的文本合理化?