shuup.xtheme package

Subpackages

Submodules

shuup.xtheme.cache module

shuup.xtheme.cache.bump_xtheme_cache(*args, **kwargs)[source]

shuup.xtheme.editing module

shuup.xtheme.editing.could_edit(request)[source]

Return true if the context of the given request would allow Xtheme editing.

Parameters:

request (django.http.HttpRequest) – HTTP request

Returns:

Would allow editing?

Return type:

bool

shuup.xtheme.editing.is_edit_mode(request)[source]

Return true if the given request has xtheme editing enabled.

Parameters:

request (django.http.HttpRequest) – HTTP request

Returns:

In edit mode?

Return type:

bool

shuup.xtheme.editing.set_edit_mode(request, flag)[source]

Enable or disable edit mode for the request.

Parameters:
shuup.xtheme.editing.may_inject(context)[source]

Figure out if we may inject Xtheme editing into this view.

The requirements are that there is a CBV view object in the context, and that view object does not explicitly opt-out of editing with xtheme_injection = False

Parameters:

context (jinja2.runtime.Context) – Jinja rendering context

Returns:

Permission bool

Return type:

bool

shuup.xtheme.editing.can_edit(context)[source]
shuup.xtheme.editing.add_edit_resources(context)[source]

Possibly inject Xtheme editor injection resources into the given context’s resources.

Parameters:

context (jinja2.runtime.Context) – Jinja rendering context

shuup.xtheme.engine module

shuup.xtheme.engine.concat(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

class shuup.xtheme.engine.XthemeTemplate(source: str | ~jinja2.nodes.Template, block_start_string: str = '{%', block_end_string: str = '%}', variable_start_string: str = '{{', variable_end_string: str = '}}', comment_start_string: str = '{#', comment_end_string: str = '#}', line_statement_prefix: str | None = None, line_comment_prefix: str | None = None, trim_blocks: bool = False, lstrip_blocks: bool = False, newline_sequence: te.Literal['\n', '\r\n', '\r'] = '\n', keep_trailing_newline: bool = False, extensions: ~typing.Sequence[str | ~typing.Type[Extension]] = (), optimized: bool = True, undefined: ~typing.Type[~jinja2.runtime.Undefined] = <class 'jinja2.runtime.Undefined'>, finalize: ~typing.Callable[[...], ~typing.Any] | None = None, autoescape: bool | ~typing.Callable[[str | None], bool] = False, enable_async: bool = False)[source]

Bases: Template

A subclass of Jinja templates with additional post-processing magic.

render(*args, **kwargs)[source]

Render the template and postprocess it.

Returns:

Rendered markup

Return type:

str

class shuup.xtheme.engine.XthemeEnvironment(block_start_string: str = '{%', block_end_string: str = '%}', variable_start_string: str = '{{', variable_end_string: str = '}}', comment_start_string: str = '{#', comment_end_string: str = '#}', line_statement_prefix: str | None = None, line_comment_prefix: str | None = None, trim_blocks: bool = False, lstrip_blocks: bool = False, newline_sequence: te.Literal['\n', '\r\n', '\r'] = '\n', keep_trailing_newline: bool = False, extensions: ~typing.Sequence[str | ~typing.Type[Extension]] = (), optimized: bool = True, undefined: ~typing.Type[~jinja2.runtime.Undefined] = <class 'jinja2.runtime.Undefined'>, finalize: ~typing.Callable[[...], ~typing.Any] | None = None, autoescape: bool | ~typing.Callable[[str | None], bool] = False, loader: BaseLoader | None = None, cache_size: int = 400, auto_reload: bool = True, bytecode_cache: BytecodeCache | None = None, enable_async: bool = False)[source]

Bases: Environment

Overrides the usual template class and allows dynamic switching of Xthemes.

Enable by adding "environment": "shuup.xtheme.engine.XthemeEnvironment" in your TEMPLATES settings.

template_class

alias of XthemeTemplate

get_template(name, parent=None, globals=None)[source]

Load a template from the loader. If a loader is configured this method asks the loader for the template and returns a Template.

Parameters:
  • name (str) – Template name.

  • parent (str|None) – If the parent parameter is not None, join_path is called to get the real template name before loading.

  • globals (dict|None) – The globals parameter can be used to provide template wide globals. These variables are available in the context at render time.

Returns:

Template object

Return type:

shuup.xtheme.engine.XthemeTemplate

get_or_select_template(template_name_or_list, parent=None, globals=None)[source]

Does a typecheck and dispatches to select_template or get_template.

Parameters:
  • template_name_or_list (str|Iterable[str]) – Template name or list

  • parent (str|None) – If the parent parameter is not None, join_path is called to get the real template name before loading.

  • globals – The globals parameter can be used to provide template wide globals. These variables are available in the context at render time.

Returns:

Template object

Return type:

shuup.xtheme.engine.XthemeTemplate

shuup.xtheme.extenders module

class shuup.xtheme.extenders.MenuExtenderLocation(value)[source]

Bases: Enum

MAIN_MENU = 1
ADMIN_MENU = 2
LEFT_MENU = 3
FOOTER = 4
class shuup.xtheme.extenders.FrontMenuExtender[source]

Bases: object

location = 1
items = []
menu_item_template = 'menu_extension.jinja'
get_rendered_menu_items(request, theme)[source]

shuup.xtheme.forms module

class shuup.xtheme.forms.GenericThemeForm(**kwargs)[source]

Bases: ModelForm

A generic form for Xthemes; populates itself based on fields in the theme class.

class Meta[source]

Bases: object

model

alias of ThemeSettings

fields = ()
__init__(**kwargs)[source]
save(commit=True)[source]

Save theme settings into the ThemeSettings instance.

Parameters:

commit (bool) – Commit flag. Default is True and will raise a ValueError if it is defined in any way. This field is here only to ensure the compatibility with the superclass.

Returns:

The now saved ThemeSettings instance

Return type:

shuup.xtheme.models.ThemeSettings

base_fields = {}
declared_fields = {}
property media

Return all media required to render the widgets on this form.

class shuup.xtheme.forms.FontForm(*args, **kwargs)[source]

Bases: ModelForm

class Meta[source]

Bases: object

model

alias of Font

fields = '__all__'
__init__(*args, **kwargs)[source]
save(commit=True)[source]

Save this form’s self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance.

base_fields = {'css_value': <django.forms.fields.CharField object>, 'eot': <filer.fields.file.AdminFileFormField object>, 'name': <django.forms.fields.CharField object>, 'shop': <django.forms.models.ModelChoiceField object>, 'svg': <filer.fields.file.AdminFileFormField object>, 'ttf': <filer.fields.file.AdminFileFormField object>, 'woff': <filer.fields.file.AdminFileFormField object>, 'woff2': <filer.fields.file.AdminFileFormField object>}
declared_fields = {}
property media

Return all media required to render the widgets on this form.

class shuup.xtheme.forms.QuickAddFontSelect(attrs=None, choices=(), editable_model=None, initial=None, model=None)[source]

Bases: QuickAddRelatedObjectSelect

Parameters:

int (initial) – primary key of the object that is initially selected

url = '/sa/xtheme/font/new/'
model = 'xtheme.Font'
property media
class shuup.xtheme.forms.AdminThemeForm(*args, **kwargs)[source]

Bases: ModelForm

class Meta[source]

Bases: object

model

alias of AdminThemeSettings

fields = '__all__'
labels = {'danger_color': 'Choose the danger (red) style primary color:', 'primary_color': 'Choose the primary color:', 'secondary_color': 'Choose the secondary color:', 'success_color': 'Choose the success (green) style primary color:', 'text_color': 'Choose the primary text color:'}
widgets = {'danger_color': <django.forms.widgets.TextInput object>, 'primary_color': <django.forms.widgets.TextInput object>, 'secondary_color': <django.forms.widgets.TextInput object>, 'success_color': <django.forms.widgets.TextInput object>, 'text_color': <django.forms.widgets.TextInput object>}
__init__(*args, **kwargs)[source]
base_fields = {'active': <django.forms.fields.BooleanField object>, 'admin_body_font': <django.forms.models.ModelChoiceField object>, 'admin_header_font': <django.forms.models.ModelChoiceField object>, 'base_font_size': <django.forms.fields.CharField object>, 'danger_color': <django.forms.fields.CharField object>, 'primary_color': <django.forms.fields.CharField object>, 'secondary_color': <django.forms.fields.CharField object>, 'shop': <django.forms.models.ModelChoiceField object>, 'success_color': <django.forms.fields.CharField object>, 'text_color': <django.forms.fields.CharField object>}
declared_fields = {}
property media

Return all media required to render the widgets on this form.

shuup.xtheme.middleware module

class shuup.xtheme.middleware.XthemeMiddleware(get_response=None)[source]

Bases: MiddlewareMixin

Handle Shuup specific tasks for each request and response.

This middleware requires the ShuupMiddleware or some other that can set the current shop in the request

process_request(request)[source]

shuup.xtheme.models module

class shuup.xtheme.models.SnippetType[source]

Bases: object

InlineJS = 'inline_js'
InlineCSS = 'inline_css'
InlineHTMLMarkup = 'inline_html'
InlineJinjaHTMLMarkup = 'inline_jinja_html'
class shuup.xtheme.models.SavedViewConfigQuerySet(model=None, query=None, using=None, hints=None)[source]

Bases: QuerySet

appropriate(theme, shop, view_name, draft)[source]

Get an “appropriate” SavedViewConfig for the parameters given.

When draft mode is off:

  • A PUBLIC SavedViewConfig is returned, or a new one in CURRENT_DRAFT status.

When draft mode is on:

  • A CURRENT_DRAFT SavedViewConfig is returned, if one exists.

  • If a PUBLIC SavedViewConfig exists, its data is copied into a new, unsaved CURRENT_DRAFT SavedViewConfig.

Parameters:
Returns:

SavedViewConfig (possibly not saved).

Return type:

SavedViewConfig

class shuup.xtheme.models.SavedViewConfigStatus(value)[source]

Bases: Enum

Stati for SavedViewConfigs.

The lifecycle for SavedViewConfigs (SVCs) for a given (theme, view) pair is as follows:

  • Initially, there’s zero SVCs.

  • When a placeholder layout is saved in edit mode, an SVC in the CURRENT_DRAFT status is saved.

  • When an SVC in CURRENT_DRAFT status is published, all other SVCs for the theme/view pair are “demoted” to being OLD_VERSIONs and the CURRENT_DRAFT SVC is promoted to being the PUBLIC one (and there should always be zero or one PUBLIC SavedViewConfigs per (theme, view) pair).

  • When an SVC in CURRENT_DRAFT status is reverted, it is simply deleted.

  • When an SVC has been published and edit mode is entered again, the current PUBLIC SVC is copied into a new CURRENT_DRAFT version.

CURRENT_DRAFT = 1
OLD_VERSION = 2
PUBLIC = 3
class shuup.xtheme.models.SavedViewConfig(id, theme_identifier, shop, view_name, created_on, modified_on, status, _data)[source]

Bases: Model

theme_identifier

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

shop

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

view_name

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

created_on

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

modified_on

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

status
objects = <django.db.models.manager.ManagerFromSavedViewConfigQuerySet object>
property draft
publish()[source]
revert()[source]
set_layout_data(layout_data_key, layout)[source]
get_layout_data(layout_data_key)[source]
clear_layout_data(placeholder_name)[source]
exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

get_next_by_created_on(*, field=<django.db.models.fields.DateTimeField: created_on>, is_next=True, **kwargs)
get_next_by_modified_on(*, field=<django.db.models.fields.DateTimeField: modified_on>, is_next=True, **kwargs)
get_previous_by_created_on(*, field=<django.db.models.fields.DateTimeField: created_on>, is_next=False, **kwargs)
get_previous_by_modified_on(*, field=<django.db.models.fields.DateTimeField: modified_on>, is_next=False, **kwargs)
get_status_display(*, field=<enumfields.fields.EnumIntegerField: status>)
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

shop_id
class shuup.xtheme.models.ThemeSettings(id, theme_identifier, shop, active, data)[source]

Bases: Model

theme_identifier

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

shop

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

active

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

data

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

activate()[source]
get_setting(key, default=None)[source]
get_settings()[source]
update_settings(update_values)[source]
exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
shop_id
class shuup.xtheme.models.Font(id, shop, name, css_value, woff, woff2, ttf, svg, eot)[source]

Bases: Model

shop

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

name

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

css_value

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

woff

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

woff2

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

ttf

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

svg

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

eot

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

get_font_sources()[source]
exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

admin_body_font

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

admin_header_font

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

eot_id
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
shop_id
svg_id
ttf_id
woff2_id
woff_id
class shuup.xtheme.models.AdminThemeSettings(id, shop, primary_color, secondary_color, text_color, success_color, danger_color, admin_header_font, admin_body_font, base_font_size, active)[source]

Bases: Model

shop

Accessor to the related object on the forward side of a one-to-one relation.

In the example:

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

primary_color

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

secondary_color

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

text_color

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

success_color

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

danger_color

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

admin_header_font

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

admin_body_font

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

base_font_size

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

active

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

colored_name(field)[source]
classmethod object()[source]
save(*args, **kwargs)[source]

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

admin_body_font_id
admin_header_font_id
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
shop_id
class shuup.xtheme.models.Snippet(*args, **kwargs)[source]

Bases: Model

Inject snippet code globally filtering by themes if configured.

name

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

shop

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

location

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

snippet_type

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

snippet

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

themes

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

blocked_gdpr_cookies

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example:

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

get_snippet_type_display(*, field=<django.db.models.fields.CharField: snippet_type>)
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
shop_id

shuup.xtheme.parsing module

exception shuup.xtheme.parsing.Unflattenable[source]

Bases: Exception

Exception raised when a node list can’t be flattened into a constant.

exception shuup.xtheme.parsing.NonConstant[source]

Bases: ValueError

Exception raised when something expected to be constant… is not.

exception shuup.xtheme.parsing.NestingError[source]

Bases: ValueError

Exception raised when a template’s placeholder/column/row/plugin hierarchy is out of whack.

shuup.xtheme.parsing.flatten_const_node_list(environment, node_list)[source]

Try to flatten the given node list into a single string.

Parameters:
  • environment (jinja2.environment.Environment) – Jinja2 environment.

  • node_list (list[jinja2.nodes.Node]) – List of nodes.

Returns:

String of content.

Return type:

str

Raises:

Unflattenable – Raised when the node list can’t be flattened into a constant.

shuup.xtheme.parsing.parse_constantlike(environment, parser)[source]

Parse the next expression as a “constantlike” expression.

Expression trees that fold into constants are constantlike, as are bare variable names.

Parameters:
  • environment (jinja2.environment.Environment) – Jinja2 environment.

  • parser (jinja2.parser.Parser) – Template parser.

Returns:

Constant value of any type.

Return type:

object

shuup.xtheme.parsing.noop_node(lineno)[source]

Return a no-op node (compiled into a single 0).

Parameters:

lineno (int) – Line number for the node.

Returns:

Node

Return type:

jinja2.nodes.ExprStmt

class shuup.xtheme.parsing.PlaceholderExtension(environment: Environment)[source]

Bases: _PlaceholderManagingExtension

PlaceholderExtension manages {% placeholder <NAME> [global] %}

{% endplaceholder %}.

  • The name can be any Jinja2 expression that can be folded into a constant, with the addition of bare variable names such as name meaning the same as "name". This makes it slightly easier to write templates.

  • The body of this block is actually discarded; only the inner column, row and plugin directives have any meaning. (A parser-time Layout object is created and populated during parsing of this block.)

  • An optional global parameter can be used to specify that the configuration for this placeholder should be “global” across different views (although currently that only applies to placeholders within the same template, i.e, if you defined the same global placeholder in different templates they will not share configuration, but an included or base template that is rendered by different views will).

tags: t.Set[str] = {'placeholder'}

if this extension parses this is the list of tags it’s listening to.

parse(parser)[source]

Parse a placeholder!

Parameters:

parser (jinja2.parser.Parser) – Template parser.

Returns:

Output node for rendering a placeholder.

Return type:

jinja2.nodes.Output

identifier: t.ClassVar[str] = 'shuup.xtheme.parsing.PlaceholderExtension'
class shuup.xtheme.parsing.LayoutPartExtension(environment: Environment)[source]

Bases: _PlaceholderManagingExtension

Parser for row and column tags.

Syntax for the row and column tags is:

{% row %}
    {% column [SIZES] %}...{% endcolumn %}
{% endrow %}
  • Rows map to LayoutRow objects and columns map to LayoutCell.

  • For a single-cell layout, these are not necessary. {% plugin %} invocations without preceding {% row %}/{% column %} directives imply a single row and a single column.

tags: t.Set[str] = {'column', 'row'}

if this extension parses this is the list of tags it’s listening to.

parse(parser)[source]

Parse a column or row.

Parameters:

parser (jinja2.parser.Parser) – Template parser.

Returns:

A null output node.

Return type:

jinja2.nodes.Node

identifier: t.ClassVar[str] = 'shuup.xtheme.parsing.LayoutPartExtension'
class shuup.xtheme.parsing.PluginExtension(environment: Environment)[source]

Bases: _PlaceholderManagingExtension

Parser for plugin tags.

Syntax for plugin tag is:

{% plugin <NAME> %}...{% endplugin %}
  • The (optional) body of the plugin block is expected to be a Jinja2 AST that can be folded into a constant. Generally this means a single block of text ({% raw }/{% endraw %} is okay!).

  • The contents of the body, if set, must be valid TOML markup. The TOML is parsed during Jinja2 parse time into a dict, which in turn is folded into the layout description object. This means only the initial parsing of the template incurs whatever performance hit there is in parsing TOML; the Jinja2 bccache should take care of the rest.

tags: t.Set[str] = {'plugin'}

if this extension parses this is the list of tags it’s listening to.

parse(parser)[source]

Parse a column or row.

Parameters:

parser (jinja2.parser.Parser) – Template parser.

Returns:

A null output node.

Return type:

jinja2.nodes.Node

identifier: t.ClassVar[str] = 'shuup.xtheme.parsing.PluginExtension'

shuup.xtheme.rendering module

shuup.xtheme.rendering.get_view_config(context, global_type=False)[source]

Get a view configuration object for a Jinja2 rendering context.

Parameters:
  • context (jinja2.runtime.Context) – Rendering context

  • global_type (bool|False) – Boolean indicating whether this is a global type

Returns:

View config

Return type:

shuup.xtheme.view_config.ViewConfig

shuup.xtheme.rendering.render_placeholder(context, placeholder_name, default_layout=None, template_name=None, global_type=False)[source]

Render a placeholder in a given context.

See PlaceholderRenderer for argument docs.

Returns:

Markup

Return type:

Markup

class shuup.xtheme.rendering.PlaceholderRenderer(context, placeholder_name, default_layout=None, template_name=None, global_type=False)[source]

Bases: object

Main class for materializing a placeholder’s contents during template render time.

Parameters:
  • context (jinja2.runtime.Context) – Rendering context

  • placeholder_name (str) – Placeholder name

  • default_layout (Layout|dict|None) – Layout or serialized layout (from template configuration)

  • template_name (str|None) – The actual template this node was in. Used to figure out whether the placeholder lives in an extends parent, or in a child.

  • global_type (bool|False) – Boolean indicating whether this is a global placeholder

__init__(context, placeholder_name, default_layout=None, template_name=None, global_type=False)[source]
Parameters:
  • context (jinja2.runtime.Context) – Rendering context

  • placeholder_name (str) – Placeholder name

  • default_layout (Layout|dict|None) – Layout or serialized layout (from template configuration)

  • template_name (str|None) – The actual template this node was in. Used to figure out whether the placeholder lives in an extends parent, or in a child.

  • global_type (bool|False) – Boolean indicating whether this is a global placeholder

render()[source]

Get this placeholder’s rendered contents.

Returns:

Rendered markup.

Return type:

markupsafe.Markup

shuup.xtheme.resources module

class shuup.xtheme.resources.InlineScriptResource[source]

Bases: str

An inline script resource (a subclass of string).

The contents are rendered inside a <script> tag.

classmethod from_vars(var_name, *args, **kwargs)[source]

Create an InlineScriptResource assigning an object of variables into a name in the window scope.

Aside from var_name the signature of this function is similar to that of dict. Useful for configuration options, etc.

Parameters:

var_name (str) – The variable to add into global scope.

Returns:

An InlineScriptResource object.

Return type:

InlineScriptResource

class shuup.xtheme.resources.JinjaMarkupResource(template, context)[source]

Bases: object

A Jinja markup resource.

__init__(template, context)[source]
render()[source]
class shuup.xtheme.resources.InlineMarkupResource[source]

Bases: str

An inline markup resource (a subclass of string).

The contents are rendered as-is.

class shuup.xtheme.resources.InlineStyleResource[source]

Bases: str

An inline style resource (a subclass of string).

class shuup.xtheme.resources.ResourceContainer[source]

Bases: object

ResourceContainers deal with storing and rendering injected resources.

A ResourceContainer is injected into rendering contexts by XthemeTemplate (akin to how django-jinja’s Template injects request and csrf_token).

__init__()[source]
add_resource(location, resource)[source]

Add a resource into the given location.

Duplicate resources are ignored (and false is returned). Resource injection order is retained.

Parameters:
Returns:

Success flag.

Return type:

bool

render_resources(location, clean=True)[source]

Render the resources for the given location, then (by default) clean that list of resources.

Parameters:
  • location (str) – The name of the location. See KNOWN_LOCATIONS.

  • clean (bool) – Whether or not to clean up the list of resources.

Returns:

String of HTML.

shuup.xtheme.resources.inject_resources(context, content, clean=True)[source]

Inject all the resources in the context’s ResourceContainer into appropriate places in the content given.

Parameters:
  • context (jinja2.runtime.Context) – Rendering context.

  • content (str) – HTML content.

  • clean (bool) – Clean the resource container as we go?

Returns:

Possibly modified HTML content.

Return type:

str

shuup.xtheme.resources.get_resource_container(context)[source]

Get a ResourceContainer from a rendering context.

Parameters:

context (jinja2.runtime.Context) – Context.

Returns:

Resource Container.

Return type:

shuup.xtheme.resources.ResourceContainer|None

shuup.xtheme.resources.add_resource(context, location, resource)[source]

Add an Xtheme resource into the given context.

Parameters:
Returns:

Success flag.

Return type:

bool

shuup.xtheme.resources.valid_view(context)[source]

Prevent adding the global snippet in admin views and in editor view.

class shuup.xtheme.resources.SnippetBlocker[source]

Bases: object

classmethod should_block_global_snippet_injection(snippet: Snippet, context: dict) bool[source]
shuup.xtheme.resources.inject_global_snippet(context, content)[source]

shuup.xtheme.settings module

shuup.xtheme.settings.SHUUP_XTHEME_ADMIN_THEME_CONTEXT = 'shuup.xtheme.admin_module.utils.get_theme_context'

Spec string for the Xtheme admin theme context.

You can use this to determine logic around which themes are visible in your project Admin Panel. This function takes shop shuup.core.models.Shop and should return current_theme_classes and current_theme for context, where current_theme_classes is a list of shuup.xtheme.models.ThemeSettings.

shuup.xtheme.settings.SHUUP_XTHEME_EXCLUDE_TEMPLATES_FROM_RESOUCE_INJECTION = ['notify/admin/script_item_editor.jinja']

Spec to control Xtheme resource injections.

Include your template names here to prevent xtheme injecting resources. This does not expect the template to exist.

Can be useful in situations, where you have html and body HTML tags inside the actual template structure.

shuup.xtheme.signal_handlers module

shuup.xtheme.signal_handlers.handle_context_cache_item_bumped(sender, **kwargs)[source]

shuup.xtheme.template_ns module

class shuup.xtheme.template_ns.XthemeNamespace[source]

Bases: object

A template helper namespace for Xtheme-related functionality.

get_view_name(context)[source]

Get the current view’s view name (used for identifying view configurations).

Parameters:

context (jinja2.runtime.Context) – Implicit Jinja2 context

Returns:

View name string

Return type:

str

is_edit_mode(context)[source]

Get the current edit mode status.

Parameters:

context (jinja2.runtime.Context) – Implicit Jinja2 context

Returns:

Edit mode enable flag

Return type:

bool

get(context, name, default=None)[source]

Get a theme setting value.

Parameters:
  • context (jinja2.runtime.Context) – Implicit Jinja2 context

  • name (str) – Setting name

  • default (object) – Default value if setting is not found

Returns:

Value

Return type:

object

shuup.xtheme.testing module

shuup.xtheme.testing.override_current_theme_class(theme_class=<object object>, shop=None)

Context manager for overriding the currently active theme class for testing.

An instance of this class is then returned by get_current_theme.

A falsy value means None is returned from get_current_theme. This is also useful for testing.

Parameters:

theme_class (class[Theme]) – A theme class object.

shuup.xtheme.urls module

shuup.xtheme.utils module

shuup.xtheme.utils.join_css_classes(class_list)[source]

Join an iterable of truthy values by spaces, effectively creating a list of CSS classes.

The retval is sorted for cleanliness.

Parameters:

class_list (Iterable[str]) – Iterable of classes

Returns:

String

Return type:

str

shuup.xtheme.utils.get_html_attrs(attrs)[source]

Flatten a dict into HTML attributes (it’s django.forms.utils.flatatt on steroids!).

Only truthy keys and values are taken into account; list-like values are flattened with join_css_classes

Parameters:

attrs (dict[str, object]) – Attribute dict

Returns:

string ready to paste after a HTML tag open. <foo%s>!

Return type:

str

shuup.xtheme.view_config module

class shuup.xtheme.view_config.ViewConfig(theme, shop, view_name, draft, global_type=False)[source]

Bases: object

A view configuration.

Contains layout and plugin configuration for all placeholders in a given view.

This class does not directly correspond to a database model; it may act as a container for SavedViewConfig objects, and wraps the SavedViewConfig API.

Initialize a view configuration.

Parameters:
  • theme (shuup.xtheme.Theme|None) – Theme object (could be None to not touch the database).

  • shop (shuup.core.models.Shop) – Shop object.

  • view_name (str) – View name (the class name of the view).

  • draft (bool) – Load in draft mode?

  • global_type (bool|False) – Boolean indicating whether this is a global config.

__init__(theme, shop, view_name, draft, global_type=False)[source]

Initialize a view configuration.

Parameters:
  • theme (shuup.xtheme.Theme|None) – Theme object (could be None to not touch the database).

  • shop (shuup.core.models.Shop) – Shop object.

  • view_name (str) – View name (the class name of the view).

  • draft (bool) – Load in draft mode?

  • global_type (bool|False) – Boolean indicating whether this is a global config.

property saved_view_config

Get a saved view config model depending on the current parameters.

Returns:

A SavedViewConfig object for the current theme/view/draft mode, or None.

Return type:

shuup.xtheme.models.SavedViewConfig|None

get_placeholder_layouts(context, placeholder_name, default_layout=None)[source]

Get a layout objects for the given placeholder and context.

Parameters:
  • context (jinja2.runtime.Context) – Rendering context.

  • placeholder_name (str) – The name of the placeholder to load.

  • default_layout (dict|Layout) – Default layout configuration (either a dict or an actual Layout).

Returns:

List of layouts available for current placeholder and context.

Return type:

list

get_placeholder_layout(layout_cls, placeholder_name, default_layout=None, context=None, layout_data_key=None)[source]

Get a layout object for the given placeholder.

Parameters:
  • layout_cls

  • placeholder_name (str) – The name of the placeholder to load.

  • default_layout (dict|Layout) – Default layout configuration (either a dict or an actual Layout).

  • context (jinja2.runtime.Context) – Rendering context.

  • layout_data_key (str) – layout data key used for saving the layout data.

Returns:

Layout.

Return type:

Layout

save_default_placeholder_layout(placeholder_name, layout)[source]

Save a default placeholder layout (only if no data for the PH already exists).

Parameters:
  • placeholder_name (str) – Placeholder name.

  • layout (Layout|dict) – Layout or layout data.

Returns:

True if saved.

Return type:

bool

publish()[source]

Publish this revision of the view configuration as the currently public one.

Returns:

Success flag.

Return type:

bool

revert()[source]

Revert this revision of the view configuration, if it’s a draft.

Returns:

Success flag.

Return type:

bool

save_placeholder_layout(layout_data_key, layout)[source]

Save the given layout as the layout for the given placeholder.

Parameters:
  • placeholder_name (str) – The placeholder name.

  • layout (Layout|dict) – Layout object (or dict).

Module contents

class shuup.xtheme.Plugin(config)

Bases: object

A plugin that can be instantiated within a shuup.xtheme.layout.LayoutCell.

Other plugins should inherit from this class and register themselves in the xtheme_plugin provide category.

Instantiate a Plugin with the given config dictionary.

Parameters:

config (dict) – Dictionary of freeform configuration data

__init__(config)[source]

Instantiate a Plugin with the given config dictionary.

Parameters:

config (dict) – Dictionary of freeform configuration data

cacheable = False
editor_form_class

alias of GenericPluginForm

fields = []
get_cache_key(context, **kwargs) str[source]

Return a string that is used as the cache key when the plugin can be cached

get_defaults()[source]

Return the default values of this plugins configuration.

Default values will be set to the plugin’s configuration and applied to the form fields’ initial values

get_editor_form_class()[source]

Return the form class for editing this plugin.

The form class should either derive from PluginForm, or at least have a get_config() method.

Form classes without fields are treated the same way as if you’d return None, i.e. no configuration form is presented to the user.

Returns:

Editor form class

Return type:

class[forms.Form]|None

classmethod get_plugin_choices(empty_label=None)[source]

Get a sorted list of 2-tuples (identifier and name) of available Xtheme plugins.

Handy for <select> boxes.

Parameters:

empty_label (str|None) – Label for the “empty” choice. If falsy, no empty choice is prepended

Returns:

List of 2-tuples

Return type:

Iterable[tuple[str, str]]

get_translated_value(key, default=None, language=None)[source]

Get a translated value from the plugin’s configuration.

It’s assumed that translated values are stored in a {language: data, ...} dictionary in the plugin configuration blob. This is the protocol that shuup.xtheme.plugins.forms.TranslatableField uses.

If the configuration blob contains such a dictionary, but it does not contain a translated value in the requested language does not exist, the fallback value, if any, within that dictionary is tried next. Failing that, the default value is returned.

Parameters:
  • key (str) – Configuration key

  • default – Default value to return when all else fails.

  • language (str|None) – Requested language. Defaults to the active language.

Returns:

A translated value.

identifier = None
is_context_valid(context)[source]

Check that the given rendering context is valid for rendering this plugin.

By default, just checks required_context_variables.

Parameters:

context (jinja2.runtime.Context) – Rendering context

Returns:

True if we should bother trying to render this

Return type:

bool

classmethod load(identifier, theme=None)[source]

Get a plugin class based on the identifier from the xtheme_plugin provides registry.

Parameters:

identifier (str) – Plugin class identifier

Returns:

A plugin class, or None

Return type:

class[Plugin]|None

name = 'Plugin'
render(context)[source]

Return the HTML for a plugin in a given rendering context.

Parameters:

context (jinja2.runtime.Context) – Rendering context

Returns:

String of rendered content.

Return type:

str

required_context_variables = {}
set_defaults()[source]

Apply the default configuration to the current configuration.

class shuup.xtheme.TemplatedPlugin(config)

Bases: Plugin

Convenience base class for plugins that just render a “sub-template” with a given context.

Instantiate a Plugin with the given config dictionary.

Parameters:

config (dict) – Dictionary of freeform configuration data

config_copied_variables = {}
engine = None
get_context_data(context)[source]

Get a context dictionary from a Jinja2 context.

Parameters:

context (jinja2.runtime.Context) – Jinja2 rendering context

Returns:

Dict of vars

Return type:

dict[str, object]

inherited_variables = {}
render(context)[source]

Return the HTML for a plugin in a given rendering context.

Parameters:

context (jinja2.runtime.Context) – Rendering context

Returns:

String of rendered content.

Return type:

str

template_name = ''
class shuup.xtheme.Theme(theme_settings=None, shop=None)

Bases: object

Base class for all the Xtheme themes.

This class does not directly correspond to a database object; it’s used in the rendering, etc. process.

It does, however, act as a container for a ThemeSettings object that contains the actual persisted settings, etc.

Initialize this theme, with an optional ThemeSettings or Shop object. Only one should be passed.

Parameters:
  • theme_settings (ThemeSettings|None) – A theme settings object for this theme.

  • shop (Shop|None) – The shop for this theme.

__init__(theme_settings=None, shop=None)[source]

Initialize this theme, with an optional ThemeSettings or Shop object. Only one should be passed.

Parameters:
  • theme_settings (ThemeSettings|None) – A theme settings object for this theme.

  • shop (Shop|None) – The shop for this theme.

author = ''
default_style_identifier = None
default_template_dir = None
extra_config_extra_css = None
extra_config_extra_js = None
extra_config_template = None
fields = []
get_all_plugin_choices(empty_label=None)[source]

Get grouped list of 2-tuples (identifier and name) of all available Xtheme plugins.

Super handy for <select> boxes.

Parameters:

empty_label (str|None) – Label for the “empty” choice. If falsy, no empty choice is prepended.

Returns:

List of 2-tuples

Return type:

Iterable[tuple[str, str]]

get_configuration_form(form_kwargs)[source]

Return a ModelForm instance (model=ThemeSettings) for configuring this theme.

By default, returns a GenericThemeForm (a ModelForm populated from theme.fields).

Parameters:

form_kwargs (dict) – The keyword arguments that should be used for initializing the form.

Return type:

django.forms.ModelForm

get_default_style()[source]
get_global_plugin_choices(empty_label=None)[source]

Get a sorted list of 2-tuples (identifier and name) of available global Xtheme plugins.

Handy for <select> boxes.

Parameters:

empty_label (str|None) – Label for the “empty” choice. If falsy, no empty choice is prepended.

Returns:

List of 2-tuples

Return type:

Iterable[tuple[str, str]]

get_setting(key, default=None)[source]

Get a setting value for this theme.

Parameters:
  • key (str) – Setting name

  • default (object) – Default value, if the setting is not set

Returns:

Setting value

Return type:

object

get_settings()[source]

Get all the currently set settings for the theme as a dict.

Returns:

Dict of settings

Return type:

dict

get_theme_plugin_choices(empty_label=None)[source]

Get a sorted list of 2-tuples (identifier and name) of available theme specific Xtheme plugins.

Handy for <select> boxes.

Parameters:

empty_label (str|None) – Label for the “empty” choice. If falsy, no empty choice is prepended.

Returns:

List of 2-tuples

Return type:

Iterable[tuple[str, str]]

get_view(view_name)[source]

Get an extra view for this theme.

Views may be either normal Django functions or CBVs (or anything that has as_view() really). Falsy values are considered “not found”.

Parameters:

view_name (str) – View name.

Returns:

The extra view, if one exists for the given name.

Return type:

dict[str, View|callable]|None

global_placeholders = []
guide_template = None
has_images()[source]

Check if theme has images available.

Returns:

True or False

Return type:

bool

has_stylesheets()[source]
identifier = None
name = ''
plugins = []
render_menu_extensions(request, location=MenuExtenderLocation.MAIN_MENU)[source]

Render menu extensions.

Some addons want to provide items to main menu.

Parameters:

request

Return safe HTML string:

set_current()[source]

Set this theme as the active theme.

set_setting(key, value)[source]

Set a theme setting key to the value value.

Parameters:
  • key (str) – Setting name.

  • value (object) – Setting value.

set_settings(*args, **kwargs)[source]

Set a number of settings for this theme.

The arguments are exactly the same as those to dict.

Note

It’s better to call this once instead of calling set_setting several times.

property settings_obj

Get a saved settings model for this theme.

Return type:

shuup.xtheme.models.ThemeSettings

stylesheets = []
template_dir = None
shuup.xtheme.get_current_theme(shop)

Get the currently active theme object.

Parameters:

shop (shuup.core.models.Shop) – The shop to get the active theme.

Returns:

Theme object or None

Return type:

Theme

shuup.xtheme.get_theme_by_identifier(identifier, shop)

Get an instantiated theme by identifier.

Parameters:
Returns:

Theme object or None

Return type:

Theme

shuup.xtheme.set_current_theme(identifier, shop)

Activate a theme based on identifier.

Parameters:
Returns:

Activated theme

Return type:

Theme

shuup.xtheme.templated_plugin_factory(identifier, template_name, **kwargs)

A factory (akin to modelform_factory) to quickly create simple plugins.

Parameters:
  • identifier (str) – The unique identifier for the new plugin.

  • template_name (str) – The template file path this plugin should render

  • kwargs (dict) – Other arguments for the TemplatedPlugin/Plugin classes.

Returns:

New TemplatedPlugin subclass

Return type:

class[TemplatedPlugin]

shuup.xtheme.get_theme_cache_key(shop=None)
shuup.xtheme.get_middleware_current_theme()

Return the current middleware state theme.

shuup.xtheme.set_middleware_current_theme(theme)

” Set the theme as the current for this thread.