trac.web.chrome – Trac content generation for the Web

Interfaces

class trac.web.chrome.INavigationContributor

Bases: trac.core.Interface

Extension point interface for components that contribute items to the navigation.

See also trac.web.chrome.INavigationContributor extension point

get_active_navigation_item(req)

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.

get_navigation_items(req)

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 or metanav. 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. The prefix 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.

author_email(author, email_map)

Returns the author email from the email_map if author doesn’t look like an email address.

authorinfo(req, author, email_map=None, resource=None)

Format a username to HTML.

Calls Chrome.format_author to format the username, and wraps the formatted username in a span with class trac-author, trac-author-anonymous or trac-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 for EMAIL_VIEW fine-grained permissions checks.
Since 1.1.6:

accepts the optional resource keyword parameter.

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_author(req, author, resource=None, show_email=None)

Format a username in plain text.

If [trac] show_email_addresses is False, email addresses will be obfuscated when the user doesn’t have EMAIL_VIEW (for the resource) and the optional parameter show_email is None. Returns translated anonymous or none, when the author string is anonymous or evaluates to False, respectively.

Parameters:
  • req – a Request or RenderingContext object.
  • author – the author string to be formatted.
  • resource – an optional Resource object for performing fine-grained permission checks for EMAIL_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 is True.

Since 1.2:

Email addresses are obfuscated when show_email_addresses is False and req is Falsy. Previously email addresses would not be obfuscated whenever req was Falsy (typically None).

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 and generate_template_stream directly.

The generated output is suitable to pass directly to Request.send, see generate_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 (see valid_html_bytes).
  • iterable – determine whether the output should be generated in chunks or as a single str; if None, the use_chunked_encoding property will be used to determine this instead
Return type:

str or an iterable of str, depending on iterable

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.

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 is false.

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 method prepare_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' , a NewTextTemplate instance will be created. If it is set to None or to another string value, a MarkupTemplate 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.

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 if your-logo.png is located in the htdocs folder within your TracEnvironment; common/your-logo.png if your-logo.png is located in the folder mapped to the [#trac-section htdocs_location] URL. Only specifying your-logo.png is equivalent to the latter.

logo_width

Width of the header logo image in pixels.

mainnav

Configures the main navigation bar, which by default contains //Wiki//, //Timeline//, //Roadmap//, //Browse Source//, //View Tickets//, //New Ticket//, //Search// and //Admin//.

The label, href, and order attributes can be specified. Entries can be disabled by setting the value of the navigation item to disabled.

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.

metanav

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.

navigation_contributors

List of components that implement INavigationContributor

never_obfuscate_mailto

Never obfuscate mailto: links explicitly written in the wiki, even if show_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:
  • req – a Request object; if None, no request related fields will be set
  • data – user-provided dict, which can be used to override the defaults; if None, the defaults will be returned
  • ddict which is populated with the defaults; if None, an empty dict will be used
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 a dict.

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 and render_template_string directly.

Return type:the generated output is an unicode string if text is True, or a Markup string otherwise.

See also generate_fragment, which produces an output suitable to pass directly to Request.send instead.

render_template(req, filename, data, metadata=None, fragment=False, iterable=False, method=None)

Renders the filename template using data 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 and method parameters are deprecated and will be removed in Trac 1.5.1. Instead, use the metadata dictionary with keys with the same name. The method key is itself deprecated, use text=True instead of method='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, or method is 'text', or text is True, 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 use generate_template_stream to produce the output (iterable of UTF-8 encoded bytes), otherwise we use render_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 the content_type value from the legacy API (a string or None). 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 in Markup
Return type:

unicode if text is True, 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.

resizable_textareas

Make <textarea> fields resizable. Requires !JavaScript.

shared_htdocs_dir

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’‘)

shared_templates_dir

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 and href 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. If filename 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. If filename 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.

Contextual Navigation

Add a link to the chrome info that will be inserted as <link> element in the <head> of the generated HTML

trac.web.chrome.add_ctxtnav(req, elm_or_label, href=None, title=None)

Add an entry to the current page’s ctxtnav bar.

trac.web.chrome.prevnext_nav(req, prev_label, next_label, up_label=None)

Add Previous/Up/Next navigation links.

Parameters:
  • req – a Request object
  • prev_label – the label to use for left (previous) link
  • up_label – the label to use for the middle (up) link
  • next_label – the label to use for right (next) link

Miscellaneous

trac.web.chrome.accesskey(req, key)

Helper function for creating accesskey HTML attribute according to preference values

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 to link 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 of links.
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. If filename 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.