121
edits
Line 58: | Line 58: | ||
</pre> | </pre> | ||
Lastly, once you're done, | Lastly, once you're done editing your controller and have a resultset to publish, you probably want to render a page. To do this you can call render('/<template-name>.mako') from your controller body to render a view with your results. To access results from your controller, it is best to store the results in a pylons.tmpl_context object, which will make them available to your mako template. | ||
===Simple code sample=== | |||
Now, to write a simple controller that prints "Hello World" using an M-V-C stack, we need three files: | |||
* controllers/hello.py | |||
* model/hello.py | |||
* templates/hello.mako | |||
Our controller lives in: controllers/hello.py | |||
<pre> | |||
import logging | |||
from pylons import request, response, session, tmpl_context as c, url | |||
from pylons.controllers.util import abort, redirect | |||
from buildapi.lib.base import BaseController, render | |||
from buildapi.model.hello import GetMessage | |||
log = logging.getLogger(__name__) | |||
class HelloController(BaseController): | |||
def index(self): | |||
# Return a rendered template | |||
c.message = GetMessage() | |||
return render('/hello.mako') | |||
</pre> | |||
Our model lives in: model/hello.py | |||
<pre> | |||
def GetMessage(): | |||
return "Hello world!" | |||
</pre> | |||
Our view lives in: templates/hello.mako (note that the tmpl_context object is available in the template) | |||
<pre> | |||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> | |||
<html> | |||
<head> | |||
<title>Hello World!</title> | |||
</head> | |||
<body> | |||
<h1>${c.message}</h1> | |||
</body> | |||
</html> | |||
</pre> | |||
= Troubleshooting Tips = | = Troubleshooting Tips = |
edits