【问题标题】:How to pass python variable to html variable?如何将python变量传递给html变量?
【发布时间】:2013-02-28 23:35:49
【问题描述】:

我需要从python中的文本文件中读取一个url链接作为变量,并在html中使用它。 文本文件“file.txt”只包含一行“http://188.xxx.xxx.xx:8878”,这一行应该保存在变量“link”中,那么我应该在html中使用这个变量的contain,这样就可以打开链接了当我单击按钮图像“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)

【问题讨论】:

  • 该 URL 会解析到哪个页面?
  • 这个 url 是我的服务器,它是我的外部地址,有一个开放的端口。
  • 网址也可以是www.google.com,......等任何网页

标签: python html variables webserver readfile


【解决方案1】:

首先,不确定 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) 中的变量。

【讨论】:

  • 感谢您的回复,但很抱歉它不起作用。我尝试使用 return html.format(htmlText=myText, link) 但不起作用!你能重写完整的代码吗?
  • 感谢 Hoff,它现在可以工作了。在我原来的 cod 中,变量“myText =' '”将根据一些“if”条件具有一个新的字符串值,因此我必须使用“return html” .format(htmlText=myText)"。所以有另一种解决方案,让我使用 return html.format(htmlText=myText)?
  • 我也不得不说,谢谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-23
  • 2011-02-17
相关资源
最近更新 更多