【问题标题】:CherryPy variables in htmlhtml中的CherryPy变量
【发布时间】:2009-10-23 01:44:36
【问题描述】:

我有一个cherryPy 程序,它返回一个在表格中包含图像(绘图)的页面。我还想在表中包含描述情节的变量。我没有使用任何模板,只是想让它变得非常简单。在下面的示例中,我有我想要的变量 numberofapplicants 但它不输出表中变量的值。我还没有找到任何关于如何做到这一点的例子。 谢谢你的帮助 文森特

 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>
    '''

【问题讨论】:

    标签: python cherrypy


    【解决方案1】:

    假设您使用的是 Python 2.x,只需使用常规字符串格式。

    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}
    

    【讨论】:

    • 我对 html 几乎一无所知,这个答案非常有帮助。工作完美。要了解有关此的更多信息,我假设我会阅读有关 html 常规字符串格式的信息,有什么建议吗?谢谢文森特
    • 基础是,如果你有一个带有%s 的字符串,那么你可以用string % replacement 语法替换它。所以,你可以"Hello, %s!" % "World",或者,如果你想要很多替换,"%s, %s!" % ("Hello", "World")。由于这很难管理,您可以命名您的替换并使用字典作为替换:"%(first)s, %(second)!" % {"first": "Hello", "second", "World"}。有关更多信息,请参阅 docs.python.org/library/…diveintopython.org/native_data_types/formatting_strings.html
    【解决方案2】:

    您的变量 'numberofapplicants' 看起来就像 Python 中字符串的其余部分。如果您想将 'numberofapplicants' 放入该位置,请使用 the % syntax,例如

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 2011-09-25
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 2011-04-10
      • 2012-09-02
      相关资源
      最近更新 更多