Commit 55506c2e authored by Evan Simpson's avatar Evan Simpson

Created PageTemplateFile module and class.

Implemented alternate path '|' operator.
Added 'default' builtin.
Made Expression types available to python expressions as functions.
Changed the way render() calls DTML.
parent 462ba6d5
......@@ -87,7 +87,7 @@
HTML- and XML-based template objects using TAL, TALES, and METAL.
"""
__version__='$Revision: 1.9 $'[11:-2]
__version__='$Revision: 1.10 $'[11:-2]
import os, sys, traceback, pprint
from TAL.TALParser import TALParser
......@@ -142,7 +142,7 @@ class PageTemplate:
def pt_render(self, source=0, extra_context={}):
"""Render this Page Template"""
if self._v_errors:
return self.pt_diagnostic()
raise RuntimeError, 'Page Template %s has errors.' % self.id
output = StringIO()
c = self.pt_getContext()
c.update(extra_context)
......@@ -163,12 +163,6 @@ class PageTemplate:
def pt_errors(self):
return self._v_errors
def pt_diagnostic(self):
return ('<html><body>\n'
'<h4>Page Template Diagnostics</h4>\n'
'<pre> %s\n</pre>'
'</body></html>\n') % join(self._v_errors, ' \n')
def write(self, text):
assert type(text) is type('')
if text[:len(self._error_start)] == self._error_start:
......
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations. All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
# notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions, and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
# in any manner possible. Zope includes a "Powered by Zope"
# button that is installed by default. While it is not a license
# violation to remove this button, it is requested that the
# attribution remain. A significant investment has been put
# into Zope, and this effort will continue if the Zope community
# continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
# features derived from or use of this software must display
# the following acknowledgement:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# In the event that the product being advertised includes an
# intact Zope distribution (with copyright and license included)
# then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
# endorse or promote products derived from this software without
# prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
# the following acknowledgment:
#
# "This product includes software developed by Digital Creations
# for use in the Z Object Publishing Environment
# (http://www.zope.org/)."
#
# Intact (re-)distributions of any official Zope release do not
# require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
# patches to official Zope releases. Distributions that do not
# clearly separate the patches from the original work must be clearly
# labeled as unofficial distributions. Modifications which do not
# carry the name Zope may be packaged in any form, as long as they
# conform to all of the clauses above.
#
#
# Disclaimer
#
# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations. Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
"""Filesystem Page Template module
Zope object encapsulating a Page Template from the filesystem.
"""
__version__='$Revision: 1.1 $'[11:-2]
import os, AccessControl, Acquisition, sys
from Globals import package_home, DevelopmentMode
from zLOG import LOG, ERROR, INFO
from string import join, strip, rstrip, split, replace, lower
from Shared.DC.Scripts.Script import Script, BindingsUI
from Shared.DC.Scripts.Signature import FuncCode
from AccessControl import getSecurityManager
from OFS.Traversable import Traversable
from PageTemplate import PageTemplate
from ZopePageTemplate import SecureModuleImporter
from ComputedAttribute import ComputedAttribute
class PageTemplateFile(Script, PageTemplate, Traversable):
"Zope wrapper for filesystem Page Template using TAL, TALES, and METAL"
meta_type = 'Page Template (File)'
func_defaults = None
func_code = FuncCode((), 0)
_need__name__=1
_v_last_read=0
_default_bindings = {'name_subpath': 'traverse_subpath'}
security = AccessControl.ClassSecurityInfo()
security.declareObjectProtected('View')
security.declareProtected('View', '__call__')
security.declareProtected('View management screens',
'read', 'document_src')
def __init__(self, filename, _prefix=None, **kw):
self.ZBindings_edit(self._default_bindings)
if _prefix is None: _prefix=SOFTWARE_HOME
elif type(_prefix) is not type(''):
_prefix = package_home(_prefix)
name = kw.get('__name__')
if not name:
name = os.path.split(filename)[-1]
self.__name__ = name
self.filename = filename = os.path.join(_prefix, filename + '.zpt')
def pt_getContext(self):
root = self.getPhysicalRoot()
c = {'template': self,
'here': self._getContext(),
'container': self._getContainer(),
'nothing': None,
'options': {},
'root': root,
'request': getattr(root, 'REQUEST', None),
'modules': SecureModuleImporter,
}
return c
def _exec(self, bound_names, args, kw):
"""Call a Page Template"""
self._cook_check()
if not kw.has_key('args'):
kw['args'] = args
bound_names['options'] = kw
try:
self.REQUEST.RESPONSE.setHeader('content-type',
self.content_type)
except AttributeError: pass
# Execute the template in a new security context.
security=getSecurityManager()
security.addContext(self)
try:
return self.pt_render(extra_context=bound_names)
finally:
security.removeContext(self)
def _cook_check(self):
if self._v_last_read and not DevelopmentMode:
return
__traceback_info__ = self.filename
try: mtime=os.stat(self.filename)[8]
except: mtime=0
if mtime == self._v_last_read:
return
self.pt_edit(open(self.filename), None)
self._cook()
self._v_last_read = mtime
def document_src(self, REQUEST=None, RESPONSE=None):
"""Return expanded document source."""
if RESPONSE is not None:
RESPONSE.setHeader('Content-Type', self.content_type)
return self.read()
def _get__roles__(self):
imp = getattr(aq_parent(aq_inner(self)),
'%s__roles__' % self.__name__)
if hasattr(imp, '__of__'):
return imp.__of__(self)
return imp
__roles__ = ComputedAttribute(_get__roles__, 1)
def __setstate__(self, state):
raise StorageError, ("Instance of AntiPersistent class %s "
"cannot be stored." % self.__class__.__name__)
......@@ -87,7 +87,7 @@
An implementation of a generic TALES engine
"""
__version__='$Revision: 1.9 $'[11:-2]
__version__='$Revision: 1.10 $'[11:-2]
import re, sys, ZTUtils
from MultiMapping import MultiMapping
......@@ -106,6 +106,8 @@ class TALESError(Exception):
return '%s on %s in "%s"' % (self.type, self.value,
self.expression)
return self.expression
def __nonzero__(self):
return 0
class Undefined(TALESError):
'''Exception raised on traversal of an undefined path'''
......@@ -121,8 +123,22 @@ class RegistrationError(Exception):
class CompilerError(Exception):
'''TALES Compiler Error'''
class SecureMultiMap:
'''MultiMapping wrapper with security declarations'''
class Default:
'''Retain Default'''
def __nonzero__(self):
return 0
Default = Default()
_marker = []
class SafeMapping(MultiMapping):
'''Mapping with security declarations and limited method exposure.
Since it subclasses MultiMapping, this class can be used to wrap
one or more mapping objects. Restricted Python code will not be
able to mutate the SafeMapping or the wrapped mappings, but will be
able to read any value.
'''
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, *dicts):
self._mm = apply(MultiMapping, dicts)
......@@ -196,10 +212,7 @@ class Engine:
except KeyError:
raise CompilerError, (
'Unrecognized expression type "%s".' % type)
try:
return handler(type, expr, self)
except TypeError:
return handler(type, expr)
def getContext(self, contexts=None, **kwcontexts):
if contexts is not None:
......@@ -220,21 +233,23 @@ class Context:
def __init__(self, engine, contexts):
self._engine = engine
self.contexts = contexts
contexts['nothing'] = None
contexts['default'] = Default
# Keep track of what contexts get pushed as each scope begins.
self._ctxts_pushed = []
# These contexts will need to be pushed.
self._current_ctxts = {'local': 1, 'repeat': 1}
contexts['local'] = lv = SecureMultiMap()
lv = self._context_class()
init_local = contexts.get('local', None)
if init_local:
lv._push(init_local)
contexts['repeat'] = rep = SecureMultiMap()
contexts['local'] = lv
contexts['repeat'] = rep = self._context_class()
contexts['loop'] = rep # alias
contexts['global'] = gv = contexts.copy()
gv['standard'] = contexts
contexts['var'] = SecureMultiMap(gv, lv)
contexts['var'] = self._context_class(gv, lv)
def beginScope(self):
oldctxts = self._current_ctxts
......@@ -254,19 +269,13 @@ class Context:
ctx.clear()
def setLocal(self, name, value):
if value is not Undefined:
self._current_ctxts['local'][name] = value
def setGlobal(self, name, value):
if value is not Undefined:
self.contexts['global'][name] = value
def setRepeat(self, name, expr):
expr = self.evaluate(expr)
if expr is Undefined:
# Not sure of this
it = self._engine.Iterator(name, [Undefined], self)
else:
it = self._engine.Iterator(name, expr, self)
self._current_ctxts['repeat'][name] = it
return it
......@@ -275,7 +284,10 @@ class Context:
if type(expression) is type(''):
expression = self._engine.compile(expression)
try:
return expression(self)
v = expression(self)
if isinstance(v, Exception):
raise v
return v
except TALESError:
raise
except:
......@@ -285,13 +297,11 @@ class Context:
def evaluateBoolean(self, expr):
bool = self.evaluate(expr)
if bool is Undefined:
return bool
return not not bool
def evaluateText(self, expr):
text = self.evaluate(expr)
if text not in (None, Undefined):
if text not in (None, Default):
text = str(text)
return text
......@@ -305,12 +315,12 @@ class Context:
def getTALESError(self):
return TALESError
def getCancelAction(self):
return Undefined
def getDefault(self):
return Default
class SimpleExpr:
'''Simple example of an expression type handler'''
def __init__(self, name, expr):
def __init__(self, name, expr, engine):
self._name = name
self._expr = expr
def __call__(self, econtext):
......
......@@ -87,7 +87,7 @@
Zope object encapsulating a Page Template.
"""
__version__='$Revision: 1.7 $'[11:-2]
__version__='$Revision: 1.8 $'[11:-2]
import os, AccessControl, Acquisition, sys
from Globals import DTMLFile, MessageDialog, package_home
......@@ -149,11 +149,6 @@ class ZopePageTemplate(Script, PageTemplate, Historical, Cacheable,
'ZScriptHTML_tryForm', 'PrincipiaSearchSource',
'document_src')
pt_editForm = DTMLFile('dtml/ptEdit', globals())
manage = manage_main = pt_editForm
pt_diagnostic = DTMLFile('dtml/ptDiagnostic', globals())
security.declareProtected('Change Page Templates',
'pt_editAction', 'pt_setTitle', 'pt_edit',
'pt_upload', 'pt_changePrefs')
......@@ -168,7 +163,7 @@ class ZopePageTemplate(Script, PageTemplate, Historical, Cacheable,
if getattr(self, '_v_warnings', None):
message = ("<strong>Warning:</strong> <i>%s</i>"
% join(self._v_warnings, '<br>'))
return self.pt_editForm(self, REQUEST, manage_tabs_message=message)
return self.pt_editForm(manage_tabs_message=message)
def pt_setTitle(self, title):
title = str(title)
......@@ -183,7 +178,7 @@ class ZopePageTemplate(Script, PageTemplate, Historical, Cacheable,
if type(file) is not type(''): file = file.read()
self.write(file)
message = 'Saved changes.'
return self.pt_editForm(self, REQUEST, manage_tabs_message=message)
return self.pt_editForm(manage_tabs_message=message)
def pt_changePrefs(self, REQUEST, height=None, width=None,
dtpref_cols='50', dtpref_rows='20'):
......@@ -199,7 +194,7 @@ class ZopePageTemplate(Script, PageTemplate, Historical, Cacheable,
setc('dtpref_rows', str(rows), path='/', expires=e)
setc('dtpref_cols', str(cols), path='/', expires=e)
REQUEST.form.update({'dtpref_cols': cols, 'dtpref_rows': rows})
return apply(self.manage_main, (self, REQUEST), REQUEST.form)
return self.manage_main()
def ZScriptHTML_tryParams(self):
"""Parameters to test the script with."""
......@@ -341,9 +336,15 @@ def manage_addPageTemplate(self, id, REQUEST=None, submit=None):
REQUEST.RESPONSE.redirect(u+'/manage_main')
return ''
manage_addPageTemplateForm = DTMLFile('dtml/ptAdd', globals())
#manage_addPageTemplateForm = DTMLFile('dtml/ptAdd', globals())
def initialize(context):
from PageTemplateFile import PageTemplateFile
manage_addPageTemplateForm = PageTemplateFile('www/ptAdd', globals())
_editForm = PageTemplateFile('www/ptEdit', globals())
ZopePageTemplate.manage = _editForm
ZopePageTemplate.manage_main = _editForm
ZopePageTemplate.pt_editForm = _editForm
context.registerClass(
ZopePageTemplate,
permission='Add Page Templates',
......@@ -353,3 +354,4 @@ def initialize(context):
)
context.registerHelp()
context.registerHelpTitle('Zope Help')
<dtml-var manage_page_header>
<dtml-var expr="manage_form_title(this(), _,
form_title='Page Template Diagnostics')">
<p class="form-help">
This Page Template needs the following changes in order to operate.
</p>
<dtml-in expr="container.pt_errors()">
<p class="form-help">
&dtml-sequence-item;
</p>
</dtml-in>
<dtml-var manage_page_footer>
<html>
<body>
<div tal:define="x string:X;nil string:">
<p tal:content="x">1</p>
<p tal:content="x | nil">2</p>
<p tal:content="(if) nil | x">3</p>
<p tal:content="y/z | x">4</p>
<p tal:content="y/z | x | nil">5</p>
<p tal:attributes="name nil">Z</p>
<p tal:attributes="name y/z | nil">Z</p>
<p tal:attributes="name y/z | nothing">Z</p>
<p tal:on-error="error/value" tal:content="a/b | (if) nil | c/d">Z</p>
</div>
</body>
</html>
<html>
<body>
<div>
<p>X</p>
<p>X</p>
<p>X</p>
<p>X</p>
<p>X</p>
<p name="">Z</p>
<p name="">Z</p>
<p>Z</p>
<p>c</p>
</div>
</body>
</html>
......@@ -16,6 +16,7 @@ class ExpressionTests(unittest.TestCase):
if m & 2: mods = mods + ' exists'
if m & 4: mods = mods + ' nocall'
e.compile('(%s) %s' % (mods, p))
e.compile('path:a|b|c/d/e')
e.compile('string:Fred')
e.compile('string:A$B')
e.compile('string:a ${x/y} b ${y/z} c')
......
......@@ -189,6 +189,12 @@ class HTMLTests(unittest.TestCase):
out = t()
util.check_html(expect, out)
def checkPathAlt(self):
t = self.folder.t
t.write(read_input('CheckPathAlt.html'))
expect = read_output('CheckPathAlt.html')
out = t()
util.check_html(expect, out)
def test_suite():
......
<dtml-var manage_page_header>
<h1 tal:replace="structure here/manage_page_header">Header</h1>
<h2 tal:define="form_title string:Add Page Template"
tal:replace="structure here/manage_form_title">Form Title</h2>
<dtml-var expr="manage_form_title(this(), _,
form_title='Add Page Template',
)">
<p class="form-help">
Page Templates allow you to use simple HTML or XML attributes to
create dynamic templates. You may choose to upload the template text
......@@ -48,4 +48,4 @@ button.
</table>
</form>
<dtml-var manage_page_footer>
<h1 tal:replace="structure here/manage_page_footer">Footer</h1>
<dtml-var manage_page_header>
<dtml-var manage_tabs>
<h1 tal:replace="structure here/manage_page_header">Header</h1>
<h2 tal:define="manage_tabs_message options/manage_tabs_message | nothing"
tal:replace="structure here/manage_tabs">Tabs</h2>
<dtml-comment>Do read at top so we can catch errors</dtml-comment>
<dtml-let read=read>
<form action="&dtml-URL1;" method="post">
<form action="" method="post"
tal:define="body request/text | here/read"
tal:attributes="action request/URL1">
<input type="hidden" name=":default_method" value="pt_changePrefs">
<table width="100%" cellspacing="0" cellpadding="2" border="0">
<tr>
......@@ -14,7 +15,7 @@
</td>
<td align="left" valign="middle">
<input type="text" name="title" size="40"
value="&dtml-title;" />
tal:attributes="value request/title | here/title" />
</td>
<td align="left" valign="middle">
<div class="form-optional">
......@@ -23,7 +24,7 @@
</td>
<td align="left" valign="middle">
<input type="text" name="content_type" size="14"
value="&dtml-content_type;" />
tal:attributes="value request/content_type | here/content_type" />
</td>
</tr>
<tr>
......@@ -33,23 +34,17 @@
</div>
</td>
<td align="left" valign="middle">
<div class="form-text">
<dtml-var bobobase_modification_time fmt="%Y-%m-%d %I:%M %p">
<div class="form-text"
tal:content="python:here.bobobase_modification_time().strftime('%Y-%m-%d %I:%M %p')">1/1/2000
</div>
</td>
<td align="left" valign="top" colspan=2>
<dtml-if html>
<a href="source.html">Browse HTML source</a>
<dtml-else>
<a href="source.xml">Browse XML source</a>
</dtml-if>
<a href="source.html" tal:condition="here/html">Browse HTML source</a>
<a href="source.xml" tal:condition="not:here/html">Browse XML source</a>
<br>
<input type="hidden" name="expand:int:default" value="0">
<dtml-if expand>
<input type="checkbox" value="1" name="expand:int" checked>
<dtml-else>
<input type="checkbox" value="1" name="expand:int">
</dtml-if>
<input type="checkbox" value="1" name="expand:int"
tal:attributes="checked request/expand | here/expand">
Expand macros when editing
</td>
</tr>
......@@ -57,8 +52,9 @@
<td align="left" valign="top" colspan="4">
<div style="width: 100%;">
<textarea name="text:text" wrap="off" style="width: 100%;"
cols=<dtml-var dtpref_cols html_quote missing="50">
rows=<dtml-var dtpref_rows html_quote missing="20">>&dtml-read;</textarea>
cols="50" rows="20"
tal:attributes="cols request/form/dtpref_cols | request/dtpref_cols | default; rows request/form/dtpref_rows | request/dtpref_rows | default"
tal:content="body">Template Body</textarea>
</div>
</td>
</tr>
......@@ -66,12 +62,10 @@
<tr>
<td align="left" valign="top" colspan="4">
<div class="form-element">
<dtml-if wl_isLocked>
<em>Locked by WebDAV</em>
<dtml-else>
<input class="form-element" type="submit"
<em tal:condition="here/wl_isLocked">Locked by WebDAV</em>
<input tal:condition="not:here/wl_isLocked"
class="form-element" type="submit"
name="pt_editAction:method" value="Save Changes">
</dtml-if>
&nbsp;&nbsp;
<input class="form-element" type="submit" name="height" value="Taller">
<input class="form-element" type="submit" name="height" value="Shorter">
......@@ -82,10 +76,10 @@
</tr>
</table>
</form>
</dtml-let>
<p class="form-help">
You may upload the text for &dtml-title_and_id; using the form below.
You may upload the text for <span tal:replace="here/title_and_id" />
using the form below.
Choose an existing file from your local computer by clicking
<em>browse</em> The contents of the file should be HTML or XML. You
may click the following link to <a href="document_src">view or
......@@ -109,15 +103,13 @@ download</a> the current text.
<td></td>
<td align="left" valign="top">
<div class="form-element">
<dtml-if wl_isLocked>
<em>Locked by WebDAV</em>
<dtml-else>
<input class="form-element" type="submit" value="Upload File">
</dtml-if>
<em tal:condition="here/wl_isLocked">Locked by WebDAV</em>
<input tal:condition="not:here/wl_isLocked"
class="form-element" type="submit" value="Upload File">
</div>
</td>
</tr>
</table>
</form>
<dtml-var manage_page_footer>
<h1 tal:replace="structure here/manage_page_footer">Footer</h1>
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment