Edit the file Hello.cpy that we've created in the previous chapter, and change it to:
CherryClass Root: mask: def index(self, name="you"): <html><body> Hello, <b py-eval="name"></b> ! <form py-attr="request.base" action="" method="get"> Enter your name: <input name=name type=text><br> <input type=submit value=OK> </form> </body></html>
Recompile the file and restart the server. Now, refresh the page in your browser. You should see
Hello, you
followed by a field where you can enter some text. Enter your name and press the OK button. Now the string has changed to
Hello, "your name"
How does it work ?
This time, the index method has a parameter called name. Just like for any Python method, this parameter can have a default value (in this case, you). The first time the browser displays the page, it doesn't pass any name parameter, so name will have its default value in the function.
When you fill out the text field and hit OK, the browser will request the same page, but this time, name will be passed as a parameter and it will contain the name you entered.
Because we used method="get" in the form, the name parameter will be passed using the URL (you can check that the URL in your browser looks like: http://localhost:8000/?name=yourName).
Now, edit Hello.cpy and change method="get" to method="post". Recompile the file, restart the server and redo the test: it works exactly the same way, except that name=yourName doesn't show up in the URL. This is because we used a POST method instead of a GET method for the form.
What we've learned:
py-eval
or py-attr
. Those tags are part or the CherryPy
templating languages.
It's now time to do more intersting things with the templating languages...
See About this document... for information on suggesting changes.