How to pass python variable to html variable?

I need to read the url link from a text file in python as a variable and use it in html. The text file "file.txt" contains only one line " http: //188.xxx.xxx.xx: 8878 ", this line should be stored in the variable "link", then I must use the contents of this variable in html, so The link should be opened when I click on the image of the go_online.png button. I tried changing my code as follows, but it does not work! any help please?

#!/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) 
+4
source share
1 answer

at first, not sure if the javascript part makes any sense, just leave it. In addition, you open the p tag, but do not close it. Not sure what your template engine is, but you can just pass the variables in pure python. Also, be sure to include quotation marks around your link. So your code should look something like this:

 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 

(btw,% s are string placeholders that will be filled with the variables in% (firstString, secondString) at the end of the multi-line string.

+3
source

All Articles