views:

73

answers:

2

I have a cherryPy program that returns a page that has an image (plot) in a table. I would also like to have variables in the table that describe the plot. I am not using any templating just trying to keep it really simple. In the example below I have the variable numberofapplicants where I want it but it does not output the value of the variable in the table. I have not been able to find any examples of how to do this. Thanks for your help Vincent

 return '''
    <html>
    <body>
    <table width="400" border="1">
    <tr>
    <td>numberofapplicants</td>
    </tr>
    <tr>
    <td width="400" height="400"><img src="img/atest.png" width="400" height="400" /></td>
    </tr>
    </table>
    </body>
    </html>
    '''
+1  A: 

Assuming you're using Python 2.x, just use regular string formatting.

return '''
    <html>
    <body>
    <table width="400" border="1">
    <tr>
    <td>%(numberofapplicants)s</td>
    </tr>
    <tr>
    <td width="400" height="400"><img src="img/atest.png" width="400" height="400" /></td>
    </tr>
    </table>
    </body>
    </html>
    ''' % {"numberofapplicants": numberofapplicants}
pavpanchekha
I no nearly nothing about html, This answer is very helpful. Work perfect. To find out more about this I assume I would read about html regular string formatting, Any recomendations?ThanksVincent
Vincent
The basics are, if you have a string with `%s` inside it, that's something you can replace with the `string % replacement` syntax. So, you might to `"Hello, %s!" % "World"`, or, if you want many replacements, `"%s, %s!" % ("Hello", "World")`. Since this gets hard to manage, you can name your replacements and use a dictionary as the replacement: `"%(first)s, %(second)!" % {"first": "Hello", "second", "World"}`. For more, see http://docs.python.org/library/stdtypes.html#string-formatting-operations and http://diveintopython.org/native_data_types/formatting_strings.html.
pavpanchekha
+1  A: 

Your variable 'numberofapplicants' just looks like the rest of the string to Python. If you want to put 'numberofapplicants' into that spot, use the % syntax, e.g.

 return '''big long string of stuff...
           and on...
           <td>%i</td>
           and done.''' % numberofapplicants
Nick T