YPage dynamic pages

The Ypage language is as follows: HTML with embedded control structures. You can create these files in any character encoding that:

ISO-8859-1, ISO-8859-15 and UTF-8 are excellent examples. (also see the inputencoding declaration below).

control structure description
<%@name=value%> declaration for this page, see below
<%!-- blah --%> Ypage comment, these are ignored by the Ypage compiler, so you can use them to add explanations in your Ypage source if you want.
<%$instruction=args%> page processing instruction, see below
<%=....%> python expression (will be converted to a string), for example: <%=time.ctime()%>
<%....python code....
....
....end of code...%>
embedded python script (extra indenting will be stripped). Be careful here. The indentation style of your embedded code must match the style that is used by the Ypage compiler (set it using the indent declaration).
<%if ... : %> python script block (ends with ':' so starts new block) Note: might not produce wat you want when you're using nested if statements
<%end%> ends a python script block. Note: ends ALL nested ifs and loops!
If you want to do nested ifs/loops, you have to do it like this (because Snakelets can't guess your loop nesting level):
<%for i ...:%>
    <%for j ...:%>
        in j loop
    <%end%>
    still in i loop
<%end%>
<%if ... : %>
...
<%elif ... : %>
...
<%else : %>
...
<%end%>
if..elif..else..end block, note the END of the block! Note: might not produce wat you want when you're using nested if statements, such as those below.
<%if a:
if b:%>
Text here
<%end%>
The end statemend ends ALL ifs and loops! See above on how you must create those nested ifs and loops.
<%for x in range(10):
thing.dostuff(x) \%>
...
...
<%end%>
manual block started by using \%>, when script block doesn't end with ':'. Be careful here. The indentation style of your embedded code must match the style that is used by the Ypage compiler (you may need to set it using the indent declaration), otherwise you'll get SyntaxErrors.
<%
def func(arg):
   return 'something is '+arg
%>
...
<%=func('going on')%>
Because Python supports nested scopes, it is perfectly possible to define your own methods (functions) inside a script block. You call them in the normal way, do not use a self. prefix, because they aren't class methods.

Recognised page declarations

(must be at the top of your Ypage file): (case-insensitive)

<%@import=import cgi,os%>
<%@import=from os import path%>
page-wide imports that will be done only once when your page is constructed
<%@session=yes|no|valid|user|dontcreate%> does this page need a session? (no=no, yes=session is created if it's not there yet, valid=session must be synchronised with the browser (i.e. browser is actually using this session, it is not new), user=also requires that a user is logged in, dontcreate=use existing session, if not available do NOT create a new one). Default=yes.
<%@authorized=role1,role2%> define that this page can only be accessed when there's a user logged in (session=user is implied!) and that this user has one or more of the given privileges/roles. See authorization.
<%@authmethod=method;argument%> define the authentication method to use for this page. See authorization.
<%@gobblews=yes|no%> remove unnecessary whitespace in the output? This is whitespace between declarations, script tags, etc. (default=yes) Snakelets is usually smart enough with stripping unnecessary whitespace, but when you really need it to appear in the output, use this option. (For instance, when not creating HTML documents)
<%@outputencoding=...%> specify the output character encoding, like UTF-8 or ISO-8859-1. If you don't specify this, Python's default output encoding is used (usually ASCII) but beware that this will very likely break pages that try to use non-ASCII characters. If you want to be safe and support Unicode output, you should define a page output encoding. This declaration is also valid in a page template, but for a change in this decl in a template to become active, you also have to recompile the actual ypage(s) that use the template. Also see the global "defaultOutputEncoding" variable in webapp creation.
<%@inputencoding=...%> specify the input char encoding (in which your Ypage source has been saved), like UTF-8 or windows-1252 or ISO-8859-1, if different from Python's default encoding. NOTE: This declaration must be present in the first 10 lines of your file, otherwise it won't be recognised.
<%@contenttype=...%> specify the Content-Type of this Ypage (default: "text/html") Also valid in a page template, but for a change in this decl in a template to become active, you also have to recompile the actual ypage(s) that use the template.
<%@disposition=...%> specify the Content-Disposition (RFC 2183) of this Ypage; you can control downloads with this. For example: <%@disposition=attachment; filename="foobar.txt"%>
<%@allowcaching=yes|no%> allow the page to be cached by the browser or by proxies? Sets certain HTTP headers. (default=no; dynamic pages are not cached)
<%@indent=4spaces|8spaces|tabs%> specify the way the compiled Ypage code should be indented, this must match your embedded python indenting style. Default is TABS. If you get weird syntax errors in your Ypages, you should check this setting!
<%@errorpage="url"%> Declare that the specified URL must be used as an error page, in case an unhandled exception occurs. You'd better make sure that the error page itself can be processed without errors ;-) (if it doesn't, Snakelets will show *that* error instead)

No output of the faulty page will be displayed, it will be replaced by the error page.

The error page can access the error details trough various members on the RequestContext object: (also see sys.exc_info() )
ctx.Exception_page -- url of the page that caused the error (string)
ctx.Exception -- the exception object itself
ctx.Exception_type -- the type of the exception
ctx.Exception_value -- value of the exception
ctx.Exception_tb -- traceback object

This declaration also works from a page template (so you can set the error page once, it is then used for all pages that use the template). This is similar to setting the defaultErrorPage config item in the webapp init file.

<%@inherit=BaseClass1,BaseClass2...%> Specify one or more base classes that this Ypage should inherit from. The default base class is snakeserver.YpageEngine.Ypage. If you have not imported the base class using an explicit import declaration, it is assumed that it can be found in a python module with the same name as the class. If you use packages in your inherit declaration (for instance pageutils.PageBase) it means that Snakelets will try to load the PageBase class from the pageutils module.
<%@pagemethod=methodname%> Specify other name for the HTML generation method (default: 'create') Useful in combination with the inherit declaration, when you want a base class to handle it and call your own method in this derived page class.
<%@method=methodName(self, args...):
    ...method body statements...
%>
Use this to define a new method on the page class level (i.e. outside the normal page code method scope). That's why the self parameter is required; you're defining a class method here (not a regular function). A few method names are reserved, and should not be used, most notably create, the methods defined on the Snakelet class, and the internal Ypage methods (for details, see below at 'YPage class methods', or refer to the YpageEngine.py source file). This is an advanced feature that you rarely need, except when you need dynamic template args. See below at 'YPage Templates'.
<%@pagetemplate="templatepage.y"%>
<%@pagetemplate="tpl.y?arg1=foo&arg2=bar"%>
Specify the template to use (see below). Use a template path that is relative to the webapp's root. If it's empty or 'none': disables the default page template. It's possible to add url-escaped parameters that will be accessible from inside the page template, see below.
<%@pagetemplatearg=paramname=the parameter value%> Specify a parameter ('paramname') that will be accessible from inside the page template, see below. You can repeat this to add more parameters. This declaration is useful when you have a default page template, instead of separate explicit pagetemplate declarations.

Recognised processing instructions:

<%$include="file"%> includes the contents of the file inside the current Ypage (parses the file as an Ypage!) Inclusion is done once, at compile time. This means that you can include .y or .html pages, but NOT directory listing urls or snakelets urls. The "file" must be relative to the page you're in, for instance "../footer.y" Note that you cannot provide URL query args!
<%$call="url"%> calls another url at this point in the Ypage when it is displayed, and includes the result in the output. The url can be anything (snakelet, ypage or .html etc, or even a directory listing-path), relative to the page ("../footer.sn") or absolute ("http://www.cnn.com"). The document at the given url is retrieved and inserted every time the page is displayed! If the URL is relative to the page or starts with a '/', it is assumed that it is an internal URL and it is handled within Snakelets. Other (external) URLs are retrieved with an expensive second HTTP request. Note that you can provide URL query args! Note: the current implementation is broken and doesn't process multi-level includes correctly. Also the content-type of the page will be wrong when using page include.
<%$redirect="url"%> Stops processing the page and directly -at ypage runtime- redirects the current processing to another URL. ( "http://..../..." or "/webapp/page.y" ) Note that you can not provide URL query args!
<%$httpredirect="url"%> Stops processing the page and directly -at ypage runtime- sends a HTTP 302 redirect to the client, to let it load another URL. ( "http://..../..." or "/webapp/page.y" ) Note that you can provide URL query args!
<%$insertpagebody%> Inserts the actual page here inside the template (see below)

YPage Templates

You can assign a template to your Ypages. Templates may contain page content that is used on multiple pages to define common elements such as a menu. Using a template, you only have to define the menu once. Templating doesn't work for snakelets: if you want to use page templates for snakelet output, you have to write an Ypage instead and redirect to that ypage from within your snakelet.

When you use the pagetemplate declaration you tell Snakelets to use that template Ypage instead of just running the current Ypage. Instead, the current Ypage will be embedded in the template page. Using the insertpagebody processing instruction you tell the engine where exactly to put the actual page inside the template. If you're using a default page template (webapp config), every Ypage that has no explicit pagetemplate declaration will be templated with the specified default template. To disable a default template, use a pagetemplate declaration with an empty value or 'none'.

Output encodings: the output encoding of the template page is ignored. The output encoding specified by the actual page is used instead! (input encodings work normally ofcourse: your template can be written as UTF-8 file while the pages itself can be ASCII).

Template page parameters: You can add url-escaped parameters to the template page declaration, like: ?arg1=foo&arg2=bar (or use the separate pagetemplatearg declaration, which might be much easier because the values don't have to be url-escaped). These parameters will be available from inside your template page code as self.PageArgs (a dict, like: {'arg1':'foo', 'arg2':'bar'}).

Dynamic template page parameters using special page method: There is a special reserved page method name, templateArgs, that is used to dynamically determine the values in the PageArgs dict. When you define it, like this:

<%@method=templateArgs(self, request):
    return { .... }
%>

it will be called for each page load (with the current Request object as a parameter, so that you can use that info too if you need it, for instance the session object, the user, etc) and the dict that it creates returns is added to PageArgs. If you need this, you must define this method in the templated page, not in the template itself (it's no use there...)

YPage class methods

A compiled Ypage inherits from Snakelet, so you have access to all methods from a snakelet. Also, some additional methods and attributes are defined:

Ypage method/attribute description
self.write(object) writes the str(object) to the page. This avoids things like: ...%><%=object%><%...
self.sendError(code, message=None) send HTTP error with specified HTTP error code (int) and message (string) (page is aborted)
self.setCookie(.....) set a new cookie. See the same method from the Response for details.
self.delCookie(.....) delete a cookie on the web browser. See the same method from the Response for details.
self.getCookies() return the cookies set on the Response (usually you'll want to get them from the request: self.Request.getCookies() because that are the cookies that the browser sent to us)
self.guessMimeType(filename) Guess the mimetype for the file. See the same method from the Response for details.
self.setContentType(mimetype) Set the content-type of the result page. See the same method from the Response for details. Usually it is enough to use the <%@contenttype=...%> declaration, but if you need to set the content-type dynamically, you must use this method.
self.setHeader(header, value) Set a custom HTTP response header. See the same method from the Response for details.
self.getHeader(header) get a previously set HTTP header. See the same method from the Response for details.
self.abort(msg='') stops page processing immediately. msg is optional. (the msg will be shown as the last thing on the page)
self.Request the snakelet request object
self.RequestCtx the request's context (scope: request) unique per user and per request, destroyed after request completes
self.SessionCtx the session context (None when there is no session) unique per user, shared for all requests of this user
self.ApplicationCtx the web application's context (scope: web application) shared for all users/requests
self.WebApp the Web App itself
self.User the logged in user object (None when no user is logged in or when no session is present)
self.URLprefix the URL base for the current webapp (same as self.WebApp.getURLprefix() ) This is often used to create correct links in Ypages. However, it's easier to use the url() function instead, see below.
self.Assetprefix the URL base for the static assets of this webapp. Can be used to create correct links to static files such as images. However, it's easier to use the asset() function instead, see below.
self.PageArgs A dict of the (optional) template page arguments. Only available inside the code of a template page.


self.Ycall(URL) to easily do a <%$call="url"%> from your embedded code. This is similar to the Snakelet's include method. Note: the current implementation is broken and doesn't process multi-level includes correctly. Also the content-type of the page will be wrong when using page include.
self.Yredirect(URL) to easily do a <%$redirect="url"%> from your embedded code. This is similar to the Snakelet's redirect method.
self.Yhttpredirect(URL) to easily do a <%$httpredirect="url"%> from your embedded code. This is similar to the Response's HTTPredirect method.
url(path) create a correct URL based on the URLprefix. Example: <%=url('main.y')%>
(this is a shortcut to the mkUrl method of the webapp. Look there for more details and options)
asset(path) create a correct URL for the static asset (images, files etc) based on the Assetprefix. Example: <%=asset('logo.jpg')%>
(this is a shortcut to the mkAssetUrl method of the webapp. Look there for more details and options)

Using self in Ypages to store data

Short: you shouldn't. Long: just like Snakelets, your Ypage code has no single, local, 'personal', environment it is running in. Your Ypage may be accessed concurrently by multiple threads (though in the current implementation, this is not so-- but don't count on this!) Only use local objects to store temporary data in, never create new properties on self! What you probably want to do is to use the request context object (self.RequestCtx) to put values on - that is safe and only lasts for the duration of the request.

Deleting the Session

If you want to delete the session, use: self.Request.deleteSession() From within the Ypage, you have no access to the Response object. Every sensible action with the response can be done with page declarations.

Snakelets manual - Back to index