0

I'm trying to make a simple website demo and I have some trouble editing the html using python. The following is the string I defined to store the html (not complete because it's too long). I want to write a function that will throw a error under a certain condition, but I don't know how to insert a line in the string "page".

page="""
<html>
  <head>
    <title>Sign up</title>
    <style type="text/css">
      .label {text-align: right}
      .error {color: red}
    </style>

  </head>

  <body>
    <h2>Sign up</h2>
    <form method="post">
      <table>
        <tr>
          <td class="label">
            Username
          </td>
          <td>
            <input type="text" name="username" value="">
          </td>
          <td class="error">

          </td>
        </tr>

        <tr>
          <td class="label">
            Password
          </td>
          <td>
            <input type="password" name="password" value="">
          </td>
          <td class="error">

          </td>
        </tr>

I want to insert the line "There is an error" in the blank between these two lines:

<td class="error">

</td>

Note there are two of this group in the string. How can I insert "There is an error" in the first group using Python? Thanks.

Kai
  • 63
  • 2
  • 4
  • have a look at template engines; e.g.: http://jinja.pocoo.org/ . or use [python string formatting](https://docs.python.org/3/library/stdtypes.html#str.format). – hiro protagonist Jul 11 '17 at 06:05

1 Answers1

1

python uses C style format strings.

page="""<html>
       ......
      <td class="error">
         %s
      </td>
    </tr>"""  % "There was an error"

alternatively, you can use python string.format as

"fooo {x}".format(x="bar"). 

see (https://docs.python.org/2/library/string.html);

jinja is an excellent template engine if you've got the time. Genshi (https://genshi.edgewall.org/wiki/GenshiTutorial) is worth looking into as well.

for Jinja2:

pip install Jinja2

in python

from jinja2 import Template
page = Template("""<html> .... 
<td class="error">{{x}}</td>
""")
page.render(x="There was an error")
Xingzhou Liu
  • 1,507
  • 8
  • 12
  • Thanks for your answer. I tried the first method and it worked. But I when I tried `self.response.out.write(page % "There was an error")`(self is inherited from webapp2.RequestHandler), "%s" is printed out instead of the error message. Why can't I do it this way? – Kai Jul 11 '17 at 13:22
  • thats odd. I'd have to see more to replicate, % should blow up if it can't consume all the arguments or doesn't get enough. – Xingzhou Liu Jul 12 '17 at 03:28