trac.web.chrome
– Trac content generation for the Web¶
Interfaces¶
Bases:
trac.core.Interface
Extension point interface for components that contribute items to the navigation.
See also trac.web.chrome.INavigationContributor extension point
This method is only called for the
IRequestHandler
processing the request.It should return the name of the navigation item to be highlighted as active/current.
Should return an iterable object over the list of navigation items to add, each being a tuple in the form (category, name, text).
The category determines the location of the navigation item and can be
mainnav
ormetanav
. The name is a unique identifier that must match the string returned by get_active_navigation_item. The text is typically a link element with text that corresponds to the desired label for the navigation item, and an href.
-
class
trac.web.chrome.
ITemplateProvider
¶ Bases:
trac.core.Interface
Extension point interface for components that provide their own Jinja2 templates and/or accompanying static resources.
See also trac.web.chrome.ITemplateProvider extension point
-
get_htdocs_dirs
()¶ Return a list of directories with static resources (such as style sheets, images, etc.)
Each item in the list must be a
(prefix, abspath)
tuple. Theprefix
part defines the path in the URL that requests to these resources are prefixed with.The
abspath
is the absolute path to the directory containing the resources on the local file system.
-
get_templates_dirs
()¶ Return a list of directories containing the provided template files.
-
Components¶
The Chrome
component is in charge of generating the content of the
pages, with the help of template engines. The default engine for Trac
1.4 is Jinja2, though we’ll still support Genshi until the next
development cycle begins (Trac 1.5.1).
The high-level API for generating content is the
render_template
method, which is paired with the output of
the process_request
method. As such,
it accepts simple but versatile parameters, and generates output which
can be directly sent to the web front-end.
There’s an intermediate level API for generating fragment of
content, either HTML or text. A fragment is typically an element of a
web page, or the result for an XHR, or simply not a HTML at all but
just some text. When the output of the fragment will be sent to the
web front-end (typically when responding to XHR), use
generate_fragment
. Otherwise, when the output should be
manipulated programmatically as a string (typically integrated in a
Fragment
), use render_fragment
.
The low-level API for generating content with the Jinja2 template
engine comprises prepare_template
, which creates a
jinja2.Template
. More precisely, it combines
load_template
and populate_data
. Such a
jinja2.Template
can then be passed to either
generate_template_stream
or
render_template_string
, depending on the desired kind of
output.
For even lower-level access to the template engine, see the section The Jinja2 template engine related to Jinja2.
-
class
trac.web.chrome.
Chrome
¶ Bases:
trac.core.Component
Web site chrome assembly manager.
Chrome is everything that is not actual page content.
-
add_auto_preview
(req)¶ Setup auto-preview for
<textarea>
fields.
-
add_jquery_ui
(req)¶ Add a reference to the jQuery UI script and link the stylesheet.
-
add_textarea_grips
(req)¶ Make
<textarea class="trac-resizable">
fields resizable if enabled by configuration.
-
add_wiki_toolbars
(req)¶ Add wiki toolbars to
<textarea class="wikitext">
fields.
Returns the author email from the
email_map
ifauthor
doesn’t look like an email address.
Format a username to HTML.
Calls
Chrome.format_author
to format the username, and wraps the formatted username in aspan
with classtrac-author
,trac-author-anonymous
ortrac-author-none
.Parameters: - req – the
Request
object. - author – the author string to be formatted.
- email_map – dictionary mapping usernames to email addresses.
- resource – optional
Resource
object forEMAIL_VIEW
fine-grained permissions checks.
Since 1.1.6: accepts the optional
resource
keyword parameter.- req – the
-
auto_preview_timeout
¶ Inactivity timeout in seconds after which the automatic wiki preview triggers an update. This option can contain floating-point values. The lower the setting, the more requests will be made to the server. Set this to 0 to disable automatic preview.
-
auto_reload
¶ Automatically reload template files after modification.
-
cc_list
(cc_field)¶ Split a CC: value in a list of addresses.
-
default_dateinfo_format
¶ The date information format. Valid options are ‘relative’ for displaying relative format and ‘absolute’ for displaying absolute format. (‘’since 1.0’‘)
-
environment_created
()¶ Create the environment templates directory.
Format a username in plain text.
If
[trac]
show_email_addresses
isFalse
, email addresses will be obfuscated when the user doesn’t haveEMAIL_VIEW
(for the resource) and the optional parametershow_email
isNone
. Returns translatedanonymous
ornone
, when the author string isanonymous
or evaluates toFalse
, respectively.Parameters: - req – a
Request
orRenderingContext
object. - author – the author string to be formatted.
- resource – an optional
Resource
object for performing fine-grained permission checks forEMAIL_VIEW
. - show_email – an optional parameter that allows explicit control of e-mail obfuscation.
Since 1.1.6: accepts the optional
resource
keyword parameter.Since 1.2: Full name is returned when
[trac]
show_full_names
isTrue
.Since 1.2: Email addresses are obfuscated when
show_email_addresses
is False andreq
is Falsy. Previously email addresses would not be obfuscated wheneverreq
was Falsy (typicallyNone
).- req – a
-
format_emails
(context, value, sep=', ')¶ Normalize a list of e-mails and obfuscate them if needed.
Parameters: - context – the context in which the check for obfuscation should be done
- value – a string containing a comma-separated list of e-mails
- sep – the separator to use when rendering the list again
-
generate_fragment
(req, filename, data, text=False, domain=None)¶ Produces content ready to be sent from the given template filename and input data, with minimal overhead.
It calls
prepare_template
to augment the data with the usual helper functions that can be expected in Trac templates, including the translation helper functions adapted to the given domain, except for some of the chrome “late” data.If you don’t need that and don’t want the overhead, use
load_template
andgenerate_template_stream
directly.The generated output is suitable to pass directly to
Request.send
, seegenerate_template_stream
for details.See also
render_fragment
, which returns a string instead.
-
generate_template_stream
(template, data, text=False, iterable=None)¶ Returns the rendered template in a form that can be “sent”.
This will be either a single UTF-8 encoded
str
object, or an iterable made of chunks of the above.Parameters: - template (
jinja2.Template
) – the Jinja2 template - text – in text mode (
True
) the generated bytes will not be sanitized (seevalid_html_bytes
). - iterable – determine whether the output should be
generated in chunks or as a single
str
; ifNone
, theuse_chunked_encoding
property will be used to determine this instead
Return type: Turning off the XML/HTML auto-escape feature for variable expansions has to be disabled when loading the template (see
load_template
), so remember to stay consistent with the text parameter.- template (
-
genshi_cache_size
¶ The maximum number of templates that the template loader will cache in memory. You may want to choose a higher value if your site uses a larger number of templates, and you have enough memory to spare, or you can reduce it if you are short on memory.
(‘’deprecated, will be removed in Trac 1.5.1’‘)
-
get_all_templates_dirs
()¶ Return a list of the names of all known templates directories.
-
get_email_map
()¶ Get the email addresses of all known users.
-
get_interface_customization_files
()¶ Returns a dictionary containing the lists of files present in the site and shared templates and htdocs directories.
-
get_permission_actions
()¶ EMAIL_VIEW
permission allows for showing email addresses even if[trac] show_email_addresses
isfalse
.
-
htdocs_location
¶ Base URL for serving the core static resources below
/chrome/common/
.It can be left empty, and Trac will simply serve those resources itself.
Advanced users can use this together with [TracAdmin trac-admin ... deploy <deploydir>] to allow serving the static resources for Trac directly from the web server. Note however that this only applies to the
<deploydir>/htdocs/common
directory, the other deployed resources (i.e. those from plugins) will not be made available this way and additional rewrite rules will be needed in the web server.
-
iterable_content
(stream, text=False, **kwargs)¶ Generate an iterable object which iterates
str
instances from the given stream instance.Parameters: text – in text mode ( True
) XML/HTML auto-escape of variable expansion is disabled.If text is a string, this corresponds to the old API and we assume to have a Genshi stream. This backward compatibility behavior will be removed in Trac 1.5.1.
-
jquery_location
¶ Location of the jQuery !JavaScript library (version %(version)s).
An empty value loads jQuery from the copy bundled with Trac.
Alternatively, jQuery could be loaded from a CDN, for example: http://code.jquery.com/jquery-%(version)s.min.js, http://ajax.aspnetcdn.com/ajax/jQuery/jquery-%(version)s.min.js or https://ajax.googleapis.com/ajax/libs/jquery/%(version)s/jquery.min.js.
(‘’since 1.0’‘)
-
jquery_ui_location
¶ Location of the jQuery UI !JavaScript library (version %(version)s).
An empty value loads jQuery UI from the copy bundled with Trac.
Alternatively, jQuery UI could be loaded from a CDN, for example: https://ajax.googleapis.com/ajax/libs/jqueryui/%(version)s/jquery-ui.min.js or http://ajax.aspnetcdn.com/ajax/jquery.ui/%(version)s/jquery-ui.min.js.
(‘’since 1.0’‘)
-
jquery_ui_theme_location
¶ Location of the theme to be used with the jQuery UI !JavaScript library (version %(version)s).
An empty value loads the custom Trac jQuery UI theme from the copy bundled with Trac.
Alternatively, a jQuery UI theme could be loaded from a CDN, for example: https://ajax.googleapis.com/ajax/libs/jqueryui/%(version)s/themes/start/jquery-ui.css or http://ajax.aspnetcdn.com/ajax/jquery.ui/%(version)s/themes/start/jquery-ui.css.
(‘’since 1.0’‘)
-
load_template
(filename, text=False)¶ Retrieves a template with the given name.
This simply loads the template. If you want to make use of the “standard” Trac API for templates, also call
populate_data
, or consider using the shortcut methodprepare_template
instead.Parameters: text – in text mode ( True
) XML/HTML auto-escape of variable expansion is disabled.Note
If the
text
argument is set to a string instead of a boolean, this corresponds to the legacy API and it will be assumed that you want to load a Genshi template instead of a Jinja2 template. If text is'text'
, aNewTextTemplate
instance will be created. If it is set toNone
or to another string value, aMarkupTemplate
instance will be created and returned.This backward compatibility behavior will be removed in Trac 1.5.1.
-
logo_alt
¶ Alternative text for the header logo.
-
logo_height
¶ Height of the header logo image in pixels.
-
logo_link
¶ URL to link to, from the header logo.
-
logo_src
¶ URL of the image to use as header logo. It can be absolute, server relative or relative.
If relative, it is relative to one of the
/chrome
locations:site/your-logo.png
ifyour-logo.png
is located in thehtdocs
folder within your TracEnvironment;common/your-logo.png
ifyour-logo.png
is located in the folder mapped to the [#trac-section htdocs_location] URL. Only specifyingyour-logo.png
is equivalent to the latter.
-
logo_width
¶ Width of the header logo image in pixels.
Configures the main navigation bar, which by default contains //Wiki//, //Timeline//, //Roadmap//, //Browse Source//, //View Tickets//, //New Ticket//, //Search// and //Admin//.
The
label
,href
, andorder
attributes can be specified. Entries can be disabled by setting the value of the navigation item todisabled
.The following example renames the link to WikiStart to //Home//, links the //View Tickets// entry to a specific report and disables the //Search// entry. {{{#!ini [mainnav] wiki.label = Home tickets.href = /report/24 search = disabled }}}
See TracNavigation for more details.
Configures the meta navigation entries, which by default are //Login//, //Logout//, //Preferences//, ‘’!Help/Guide’’ and //About Trac//. The allowed attributes are the same as for
[mainnav]
. Additionally, a special entry is supported -logout.redirect
is the page the user sees after hitting the logout button. For example:{{{#!ini [metanav] logout.redirect = wiki/Logout }}}
See TracNavigation for more details.
List of components that implement
INavigationContributor
-
never_obfuscate_mailto
¶ Never obfuscate
mailto:
links explicitly written in the wiki, even ifshow_email_addresses
is false or the user doesn’t have EMAIL_VIEW permission.
-
populate_data
(req=None, data=None, d=None)¶ Fills a dictionary with the standard set of fields expected by templates.
Parameters:
-
prepare_request
(req, handler=None)¶ Prepare the basic chrome data for the request.
Parameters: - req – the request object
- handler – the
IRequestHandler
instance that is processing the request
-
prepare_template
(req, filename, data, text=False, domain=None)¶ Prepares the rendering of a Jinja2 template.
This loads the template and prepopulates a data
dict
with the “standard” Trac API for templates.Parameters: - req – a
Request
instance (optional) - filename – the name of a Jinja2 template, which must be
found in one of the template directories (see
get_templates_dirs
) - data – user specified data dictionary, used to override
the default context set from the request req
(see
populate_data
) - text – in text mode (
True
) XML/HTML auto-escape of variable expansion is disabled.
Return type: a pair of Jinja2
Template
and adict
.- req – a
-
render_fragment
(req, filename, data, text=False, domain=None)¶ Produces a string from given template filename and input data, with minimal overhead.
It calls
prepare_template
to augment the data with the usual helper functions that can be expected in Trac templates, including the translation helper functions adapted to the given domain, except for some of the chrome “late” data.If you don’t need that and don’t want the overhead, use
load_template
andrender_template_string
directly.Return type: the generated output is an unicode
string if text isTrue
, or aMarkup
string otherwise.See also
generate_fragment
, which produces an output suitable to pass directly toRequest.send
instead.
-
render_template
(req, filename, data, metadata=None, fragment=False, iterable=False, method=None)¶ Renders the
filename
template usingdata
for the context.It attempts to load a Jinja2 template, augments the provided data with standard data, and renders it according to the options provided in metadata.
The
fragment
,iterable
andmethod
parameters are deprecated and will be removed in Trac 1.5.1. Instead, use themetadata
dictionary with keys with the same name. Themethod
key is itself deprecated, usetext=True
instead ofmethod='text'
to indicate that the template is a plain text one, with no need for HTML/XML escaping to take place.When
fragment
is specified, ormethod
is'text'
, ortext
isTrue
, we generate some content which does not need all of the chrome related data, typically HTML fragments, XML or plain text.If
iterable
is set, we usegenerate_template_stream
to produce the output (iterable of UTF-8 encoded bytes), otherwise we userender_template_string
and UTF-8 encode the result.Note
If the Jinja2 template is not found, this method will try to load a Genshi template instead.
Also if
metadata
is not a dictionary, we assume that it is thecontent_type
value from the legacy API (a string orNone
). As a consequence, we assume the template will be a Genshi template and we’ll use the legacy Genshi template engine for the rendering.This backward compatibility behavior will be removed in Trac 1.5.1.
-
render_template_string
(template, data, text=False)¶ Renders the template as an unicode or Markup string.
Parameters: - template (
jinja2.Template
) – the Jinja2 template - text – in text mode (
True
) the generated string will not be wrapped inMarkup
Return type: unicode
if text isTrue
,Markup
otherwise.Turning off the XML/HTML auto-escape feature for variable expansions has to be disabled when loading the template (see
load_template
), so remember to stay consistent with the text parameter.- template (
-
resizable_textareas
¶ Make
<textarea>
fields resizable. Requires !JavaScript.
Path to the //shared htdocs directory//.
Static resources in that directory are mapped to /chrome/shared under the environment URL, in addition to common and site locations.
This can be useful in site.html for common interface customization of multiple Trac environments.
(‘’since 1.0’‘)
Path to the //shared templates directory//.
Templates in that directory are loaded in addition to those in the environments
templates
directory, but the latter take precedence.
-
show_email_addresses
¶ Show email addresses instead of usernames. If false, email addresses are obfuscated for users that don’t have EMAIL_VIEW permission.
-
show_full_names
¶ Show full names instead of usernames. (//since 1.2//)
-
stream_filters
¶ List of components that implement
ITemplateStreamFilter
-
template_providers
¶ List of components that implement
ITemplateProvider
-
use_chunked_encoding
¶ If enabled, send contents as chunked encoding in HTTP/1.1. Otherwise, send contents with
Content-Length
header after entire of the contents are rendered. (‘’since 1.0.6’‘)
-
wiki_toolbars
¶ Add a simple toolbar on top of Wiki <textarea>s. (‘’since 1.0.2’‘)
-
Functions¶
Most of the helper functions are related to content generation, and in particular, (X)HTML content generation, in one way or another.
-
trac.web.chrome.
web_context
(req, resource=None, id=False, version=False, parent=False, absurls=False)¶ Create a rendering context from a request.
The
perm
andhref
properties of the context will be initialized from the corresponding properties of the request object.>>> from trac.test import Mock, MockPerm >>> req = Mock(href=Mock(), perm=MockPerm()) >>> context = web_context(req) >>> context.href is req.href True >>> context.perm is req.perm True
Parameters: - req – the HTTP request object
- resource – the
Resource
object or realm - id – the resource identifier
- version – the resource version
- absurls – whether URLs generated by the
href
object should be absolute (including the protocol scheme and host name)
Returns: a new rendering context
Return type: RenderingContext
Since: version 1.0
-
trac.web.chrome.
add_meta
(req, content, http_equiv=None, name=None, scheme=None, lang=None)¶ Add a
<meta>
tag into the<head>
of the generated HTML.
Web resources¶
-
trac.web.chrome.
add_stylesheet
(req, filename, mimetype='text/css', **attrs)¶ Add a link to a style sheet to the chrome info so that it gets included in the generated HTML page.
If
filename
is a network-path reference (i.e. starts with a protocol or//
), the return value will not be modified. Iffilename
is absolute (i.e. starts with/
), the generated link will be based off the application root path. If it is relative, the link will be based off the/chrome/
path.
-
trac.web.chrome.
add_script
(req, filename, mimetype='text/javascript', charset='utf-8', ie_if=None)¶ Add a reference to an external javascript file to the template.
If
filename
is a network-path reference (i.e. starts with a protocol or//
), the return value will not be modified. Iffilename
is absolute (i.e. starts with/
), the generated link will be based off the application root path. If it is relative, the link will be based off the/chrome/
path.
-
trac.web.chrome.
add_script_data
(req, data={}, **kwargs)¶ Add data to be made available in javascript scripts as global variables.
The keys in
data
and the keyword argument names provide the names of the global variables. The values are converted to JSON and assigned to the corresponding variables.
Page admonitions¶
-
trac.web.chrome.
add_warning
(req, msg, *args)¶ Add a non-fatal warning to the request object.
When rendering pages, all warnings will be rendered to the user. Note that the message is escaped (and therefore converted to
Markup
) before it is stored in the request object.
-
trac.web.chrome.
add_notice
(req, msg, *args)¶ Add an informational notice to the request object.
When rendering pages, all notices will be rendered to the user. Note that the message is escaped (and therefore converted to
Markup
) before it is stored in the request object.
Miscellaneous¶
-
trac.web.chrome.
accesskey
(req, key)¶ Helper function for creating accesskey HTML attribute according to preference values
-
trac.web.chrome.
auth_link
(req, link)¶ Return an “authenticated” link to
link
for authenticated users.If the user is anonymous, returns
link
unchanged. For authenticated users, returns a link to/login
that redirects tolink
after authentication.
Internals¶
-
trac.web.chrome.
chrome_info_script
(req, use_late=None)¶ Get script elements from chrome info of the request object during rendering template or after rendering.
Parameters: - req – the HTTP request object.
- use_late – if True,
late_links
will be used instead oflinks
.
-
trac.web.chrome.
chrome_resource_path
(req, filename)¶ Get the path for a chrome resource given its
filename
.If
filename
is a network-path reference (i.e. starts with a protocol or//
), the return value will not be modified. Iffilename
is absolute (i.e. starts with/
), the generated link will be based off the application root path. If it is relative, the link will be based off the/chrome/
path.