Open source cms for mobile and desktop websites

nive.views

Basic view class for nive object views.

Use this class as base for custom view definitions for file download support, data rendering, url generation, http headers and user lookup.

exception nive.views.Unauthorized

Raised by failed logins or insufficient permissions

class nive.views.BaseView(context, request)
configuration

View module configuration

If views are registered by using ViewModuleConf.views the ViewModuleConf is automatically available as class attribute of the view instance. Any specific configuration values are avalilable directly through the configuration. E.g.

index = self.viewModule.template

returns ViewModuleConf

Url(resource=None)

Generates the default url for the resource. Includes the file extension if one specified for the object.

If resource is None the current context object is used as resource.

returns url

FolderUrl(resource=None)

Generates the default url for the resource without extension and trailing ‘/’.

If resource is None the current context object is used as resource.

returns url

StaticUrl(file)

Generates the url for a static file. file is the filename to look the url up for. E.g. for the default static directory use

   <link tal:attributes="href view.StaticUrl('layout2.css')" 
         rel="stylesheet" type="text/css" media="all" >
         
to reference a file in a different directory you must include the python module like ::

   <link tal:attributes="href view.StaticUrl('my_app.design:static/layout2.css')" 
         rel="stylesheet" type="text/css" media="all" >
         
absolute http urls can also be used based on the url prefix http, https and / ::

   <link tal:attributes="href view.StaticUrl('/assets/layout2.css')" 
         rel="stylesheet" type="text/css" media="all" >
   <link tal:attributes="href view.StaticUrl('http://myserver.com/assets/layout2.css')" 
         rel="stylesheet" type="text/css" media="all" >
   <link tal:attributes="href view.StaticUrl('https://myserver.com/assets/layout2.css')" 
         rel="stylesheet" type="text/css" media="all" >

returns url

FileUrl(fieldID, resource=None)

Generates the file url for the file contained in resource. The resource must have the ‘file’ view included (IFile). If the url is called the download is mapped to View.file.

If resource is None the current context object is used as resource.

returns url

PageUrl(resource=None, usePageLink=0, addAnchor=False)

Generates the default page url for the resource with extension. If resource is a page element the page containing this element is used for the url.

If resource is None the current context object is used as resource.

If addAnchor is true and resource is not the actula page the url is generated for, the function will append a anchor for the resource to the url based on the id.

returns url

CurrentUrl(retainUrlParams=False)

Returns the current url that triggered this request. Url parameter are removed by default.

returns url

ResolveUrl(url, object=None)

Resolve a string to url for object or the current context.

Url placeholders to be used as url

  • obj_url
  • obj_folder_url
  • parent_url
  • page_url
  • page_url_anchor

The url can also be a callable. It is called with two parameters context and view class instance. E.g.

def makeUrl(context, view):
    return view.GetUrl(context) + "?query=" + view.GetFormValue('query')

returns url

Resolve the link to a valid (page) URL. If the link is an existing object.id the url to the page containing this object is returned.

returns url

SendResponse(data, mime='text/html', filename=None, raiseException=True, status=None, headers=None)

Creates a response with data as body. If raiseException is true the function will raise a HTTPOk Exception with data as body. A custom response status can only be passed if raiseException is False.

If filename is not none the response will extended with a attachment; filename=filename header.

Redirect(url, messages=None, slot='', raiseException=True, refresh=True, force=False)

Redirect to the given URL. Messages are stored in session and can be accessed by calling request.session.pop_flash(). Messages are added by calling request.session.flash(m, slot).

Redirect automatically detects ajax requests and calls Relocate in such a case to prevent a page refresh. Set force=True to force redirects even for ajax requests.

Relocate(url, messages=None, slot='', raiseException=True, refresh=True)

Returns messages and X-Relocate header in response. If raiseException is True HTTPOk is raised with empty body.

ResetFlashMessages(slot='')

Removes all messages stored in session.

AddHeader(name, value)

Add a additional response header value.

DefaultTemplateRenderer(values, templatename=None)

Renders the default template configured in context.configuration.template with the given dictionary values. Calls CacheHeader to set the default cache headers.

Adds the following values if not set

{u"context": self.context, u"view": self} 

Template lookup first searches the current view module and if not found the parent or extended view module.

RenderView(obj, name='', secure=True, raiseUnauthorized=False, codepage='utf-8')

Render a view for the object.

name is the name of the view to be looked up.

If secure is true permissions of the current user are checked against the view. If the user lacks the necessary permissions and empty string is returned or if raiseUnauthorized is True HTTPForbidden is raised.

returns rendered result

Assets(assets=None, ignore=None, viewModuleConfID=None, types=None)

Renders a list of static ressources as html <script> and <link>. If assets is None the list of assets is looked up in the view module-configuration. Asset definitions use a identifier and an asset path like:

assets = (
  ('jquery.js', 'nive_cms.cmsview:static/mods/jquery.min.js'),
  ('toolbox.css', 'nive_cms.cmsview:static/toolbox/toolbox.css'),
  ('jquery-ui.js', 'http://example.com/static/mods/jquery.min.js')
)

If for example jquery is already included in the main page Assets() can be told to ignore certain entries:

cmsview.Assets(ignore=["jquery.js"])  

The list of assets is configured as part of the view module settings. If the view module configuration is not stored as class attribute (self.viewModule) the configuration can be accessed by id in the applications registry. In this case the id can be passed in like Assets(viewModuleConfID=’editor’) to lookup the the configuration in the registry.

By default Assets renders both css and js links. You can use the parameter types e.g types=”js” to get js file links only. Set types=”css” to get all css links.

IsPage(object=None)

Check if object is a page.

returns bool

tmpl()

Default function for template rendering.

File()

Used by “file” view for the current context.

Calls SendFile() for the file matching the filename of the current url.

SendFile(file)

Creates the response and sends the file back. Uses the FileIterator.

#!date format

CacheHeader(response, user=None)

Adds a http cache header to the response. If user is not None NoCache() is called, otherwise Modified().

returns response

NoCache(response, user=None)

Adds a no-cache header to the response.

returns response

Modified(response, user=None)

Adds a last modified header to the response. meta.pool_change is used as date.

returns response

GetViewConf(view_name=None)

Looks up the current view configuration nive.definitions.ViewConf. Please note: Unique view names on view module level are required for this function!

view_name: If None the current view_name is used. returns nive.definitions.ViewConf or None

User(sessionuser=True)

Get the currently signed in user. If sessionuser=False the function will return the uncached write enabled user from database.

returns the Authenticated User Object or None

UserName()

returns the Authenticated User Name or None

Allowed(permission, context=None)

Check if the current user has the permission for the context. If context is none the current context is used

returns True / False

InGroups(groups)

Check if current user is in one of the groups.

RenderField(fld, data=None, context=None)

Render the data field for html display. Rendering depends on the datatype defined in the field configuration.

If data is None the current context is used.

returns string

Translate(text)

Tranlate a translation string. Extracts language from request.

FmtTextAsHTML(text)

Converts newlines to <br>.

returns string

FmtDateText(date, language=None)

Formats dates as readable text in conventional format.

returns string

FmtDateNumbers(date, language=None)

Formats dates as numbers e.g 13.12.2011.

returns string

FmtSeconds(secs)

seconds to readable text

FmtBytes(size)

bytes to readable text

FmtTag(tag, closeTag='tag', **attributes)

Write a html tag with attributes. closeTag: ‘tag’, ‘inline’, ‘no’, ‘only’

CutText(text, length)

bytes to readable text

utilities

You can easily make utility functions like renderers and format functions accessible in templates by adding the functions to your view module configuration. e.g.

def renderTime(value):
    return value.strftime("%H:%M")

view_configuration = ViewModuleConf(
    id = "views",
    name = u"Views",
    # utilities
    utilities = Conf(renderTime=renderTime)
    ...
)

You can call renderTime in your template by accessing the view class instance

view.utilities.renderTime(value)
Returns:utilities mapping object
GetFormValue(key, default=None, request=None, method=None)

Extract a form field from request. Works with webob requests and simple dictionaries.

returns the value or default

GetFormValues(request=None, method=None)

Extract all form fields from request. Works with webob requests and simple dictionaries.

returns dictionary

FmtURLParam(**kw)

Format all kw items as url parameter.

returns string

FmtFormParam(**kw)

Format all kw items as hidden input fields for forms.

returns string

nive.views.SendResponse(data, mime='text/html', filename=None, raiseException=True, status=None, headers=None)

See views.BaseView class function for docs

nive.views.Redirect(url, request, messages=None, slot='', raiseException=True, refresh=True, force=False)

See views.BaseView class function for docs

nive.views.Relocate(url, request, messages=None, slot='', raiseException=True, refresh=True)

See views.BaseView class function for docs

nive.views.ResetFlashMessages(request, slot='')

See views.BaseView class function for docs

nive.views.AddHeader(request, name, value)

See views.BaseView class function for docs

class nive.views.Mail(title=u'', tmpl=None)

Mail template object with template link and title.

mail = Mail(title="New mail", tmpl="mypackage:templates/foo.pt")
body = mail(value1=1, value2=2)

the body of the mail is generated by calling the mail object. kw parameters are passed on in template.render()

© 2013 Nive GmbH