pax_global_header 0000666 0000000 0000000 00000000064 13453626426 0014525 g ustar 00root root 0000000 0000000 52 comment=d4c382cdc7c53ad595aa4fa6fe48dd8a59ca675e
django-sekizai-1.0.0/ 0000775 0000000 0000000 00000000000 13453626426 0014422 5 ustar 00root root 0000000 0000000 django-sekizai-1.0.0/.gitignore 0000664 0000000 0000000 00000000137 13453626426 0016413 0 ustar 00root root 0000000 0000000 *.pyc
*~
.*
!.gitignore
!.travis.yml
/dist/
/*.egg-info/
/*.egg/
/htmlcov/
docs/_build
/*env*/
django-sekizai-1.0.0/.travis.yml 0000664 0000000 0000000 00000001201 13453626426 0016525 0 ustar 00root root 0000000 0000000 dist: xenial
language: python
sudo: false
python:
- 2.7
- 3.4
- 3.5
- 3.6
- 3.7
env:
- DJANGO='django>=1.11,<2.0'
- DJANGO='django>=2.0,<2.1'
- DJANGO='django>=2.1,<2.2'
- DJANGO='django>=2.2a1,<3.0'
install:
- pip install $DJANGO django-classy-tags pep8 backport-collections
script: python runtests.py
notifications:
email: false
matrix:
exclude:
- python: 2.7
env: DJANGO='django>=2.0,<2.1'
- python: 2.7
env: DJANGO='django>=2.1,<2.2'
- python: 2.7
env: DJANGO='django>=2.2a1,<3.0'
- python: 3.4
env: DJANGO='django>=2.1,<2.2'
- python: 3.4
env: DJANGO='django>=2.2a1,<3.0'
django-sekizai-1.0.0/LICENSE 0000664 0000000 0000000 00000002716 13453626426 0015435 0 ustar 00root root 0000000 0000000 Copyright (c) 2010, Jonas Obrist
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Jonas Obrist nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL JONAS OBRIST BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. django-sekizai-1.0.0/MANIFEST.in 0000664 0000000 0000000 00000000147 13453626426 0016162 0 ustar 00root root 0000000 0000000 include LICENSE
include README.rst
recursive-include sekizai/test_templates *
recursive-include docs *
django-sekizai-1.0.0/README.rst 0000664 0000000 0000000 00000002304 13453626426 0016110 0 ustar 00root root 0000000 0000000 Please refer to the documentation in the docs/ directory or on `RTFD `_ for help.
About this project:
The main reason I started this project was the lack of a good media (css/js)
framework in django and the django-cms. Yes there is the Media class used in
forms in django, but really that doesn't work that well. Usually the frontend
guys want to decide on css and javascript files to be included and they don't
want to have to edit Python files to change that neither did I want them to
change my Python files. Therefore there was a need to allow you to edit contents
of templates which are before or after the point where you are now. Also I
wanted duplicates to be removed. As a result I wrote django-sekizai, which does
exactly that. It's similar to blocks, just instead of inheriting them, you
extend them.
There are some issue/restrictions with this implementation due to how the
django template language works, but if used properly it can be very useful and
it is the media handling framework for the django CMS (since version 2.2).
.. image:: https://travis-ci.org/ojii/django-sekizai.svg?branch=master
:target: https://travis-ci.org/ojii/django-sekizai
django-sekizai-1.0.0/docs/ 0000775 0000000 0000000 00000000000 13453626426 0015352 5 ustar 00root root 0000000 0000000 django-sekizai-1.0.0/docs/Makefile 0000664 0000000 0000000 00000006106 13453626426 0017015 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-sekizai.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-sekizai.qhc"
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
django-sekizai-1.0.0/docs/conf.py 0000664 0000000 0000000 00000014270 13453626426 0016655 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# django-sekizai documentation build configuration file, created by
# sphinx-quickstart on Tue Jun 29 23:12:20 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'django-sekizai'
copyright = u'2010, Jonas Obrist'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.6'
# The full version, including alpha/beta/rc tags.
release = '0.6.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'django-sekizaidoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'django-sekizai.tex', u'django-sekizai Documentation',
u'Jonas Obrist', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
django-sekizai-1.0.0/docs/index.rst 0000664 0000000 0000000 00000031600 13453626426 0017213 0 ustar 00root root 0000000 0000000 .. django-sekizai documentation master file, created by
sphinx-quickstart on Tue Jun 29 23:12:20 2010.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
##########################################
Welcome to django-sekizai's documentation!
##########################################
.. note::
If you get an error when using django-sekizai that starts with
**Invalid block tag:**, please read :ref:`restrictions`.
*****
About
*****
Sekizai means "blocks" in Japanese, and that's what this app provides. A fresh
look at blocks. With django-sekizai you can define placeholders where your
blocks get rendered and at different places in your templates append to those
blocks. This is especially useful for css and javascript. Your sub-templates can
now define css and Javascript files to be included, and the css will be nicely
put at the top and the Javascript to the bottom, just like you should. Also
sekizai will ignore any duplicate content in a single block.
************
Dependencies
************
* Django 1.11, 2.0, 2.1, or 2.2.
* django-classy-tags 0.3.1 or higher.
*****
Usage
*****
Configuration
=============
In order to get started with django-sekizai, you'll need to do the following
steps:
* Put 'sekizai' into your ``INSTALLED_APPS`` setting.
* Use one of the following:
* Add ``sekizai.context_processors.sekizai`` to your
``TEMPLATES['OPTIONS']['context_processors']`` setting and use
``django.template.RequestContext`` when rendering your templates.
or
* Use ``sekizai.context.SekizaiContext`` when rendering your templates.
Template Tag Reference
======================
.. highlight:: html+django
.. note:: All sekizai template tags require the ``sekizai_tags`` template tag
library to be loaded.
Handling code snippets
----------------------
.. versionadded:: 0.7
The ``strip`` flag was added.
Sekizai uses ``render_block`` and ``addtoblock`` to handle unique code snippets.
Define your blocks using ``{% render_block %}`` and add data to that
block using ``{% addtoblock [strip] %}...{% endaddtoblock %}``. If the
strip flag is set, leading and trailing whitespace will be removed.
Example Template::
{% load sekizai_tags %}
{% render_block "css" %}
Your content comes here.
Maybe you want to throw in some css:
{% addtoblock "css" %}
{% endaddtoblock %}
Some more content here.
{% addtoblock "js" %}
{% endaddtoblock %}
And even more content.
{% render_block "js" %}
Above example would roughly render like this::
Your content comes here.
Maybe you want to throw in some css:
Some more content here.
And even more content.
.. note::
It's recommended to have all ``render_block`` tags in your base template, the one that gets extended by all your
other templates.
.. _restrictions:
Restrictions
------------
.. warning::
``{% render_block %}`` tags **must not** be placed inside a template tag block (a template tag which has an
end tag, such as ``{% block %}...{% endblock %}`` or ``{% if %}...{% endif %}``).
.. warning::
``{% render_block %}`` tags **must not** be in an included template!
.. warning::
If the ``{% addtoblock %}`` tag is used in an **extending** template, the tags **must** be
placed within ``{% block %}...{% endblock %}`` tags.
.. warning::
``{% addtoblock %}`` tags **must not** be used in a template included with ``only`` option!
Handling data
-------------
Sometimes you might not want to use code snippets but rather just add a value to
a list. For this purpose there are the
``{% with_data as %}...{% end_with_data %}`` and
``{% add_data %}`` template tags.
Example::
{% load sekizai_tags %}
{% with_data "css-data" as stylesheets %}
{% for stylesheet in stylesheets %}
{% endfor %}
{% end_with_data %}
Your content comes here.
Maybe you want to throw in some css:
{% add_data "css-data" "css/stylesheet.css" %}
Some more content here.
Above example would roughly render like this::
Your content comes here.
Maybe you want to throw in some css:
Some more content here.
And even more content.
.. warning::
The restrictions for ``{% render_block %}`` also apply to ``{% with_data %}``, see above.
The restrictions for ``{% addtoblock %}`` also apply to ``{% add_data %}``, see above.
Sekizai data is unique
----------------------
All data in sekizai is enforced to be unique within its block namespace. This
is because the main purpose of sekizai is to handle javascript and css
dependencies in templates.
A simple example using ``addtoblock`` and ``render_block`` would be::
{% load sekizai_tags %}
{% addtoblock "js" %}
{% endaddtoblock %}
{% addtoblock "js" %}
{% endaddtoblock %}
{% addtoblock "js" %}
{% endaddtoblock %}
{% addtoblock "js" %}
{% endaddtoblock %}
{% render_block "js" %}
Above template would roughly render to::
.. versionadded:: 0.5
Processing sekizai data
-----------------------
Because of the restrictions of the ``{% render_block %}`` tag, it is not possible
to use sekizai with libraries such as django-compressor directly. For that
reason, sekizai added postprocessing capabilities to ``render_block`` in
version 0.5.
Postprocessors are callable Python objects (usually functions) that get the
render context, the data in a sekizai namespace and the name of the namespace
passed as arguments and should return a string.
An example for a processor that uses the Django builtin spaceless functionality
would be:
.. code-block:: python
def spaceless_post_processor(context, data, namespace):
from django.utils.html import strip_spaces_between_tags
return strip_spaces_between_tags(data)
To use this post processor you have to tell ``render_block`` where it's
located. If above code sample lives in the Python module
``myapp.sekizai_processors`` you could use it like this::
...
{% render_block "js" postprocessor "myapp.sekizai_processors.spaceless_post_processor" %}
...
It's also possible to pre-process data in ``{% addtoblock %}`` like this::
{% addtoblock "css" preprocessor "myapp.sekizai_processors.processor" %}
*******
Helpers
*******
:mod:`sekizai.helpers`
======================
.. function:: get_namespaces(template)
Returns a list of all sekizai namespaces found in ``template``, which should
be the name of a template. This method also checks extended templates.
.. function:: validate_template(template, namespaces)
Returns ``True`` if all namespaces given are found in the template given.
Useful to check that the namespaces required by your application are
available, so you can failfast if they're not.
*******
Example
*******
.. highlight:: html+django
A full example on how to use django-sekizai and when.
Let's assume you have a website, where all templates extend base.html, which
just contains your basic HTML structure. Now you also have a small template
which gets included on some pages. This template needs to load a javascript
library and execute some specific javascript code.
Your ``base.html`` might look like this::
{% load sekizai_tags %}
Your website
{% render_block "css" %}
{% block "content" %}
{% endblock %}
{% render_block "js" %}
As you can see, we load ``sekizai_tags`` at the very beginning. We have two
sekizai namespaces: "css" and "js". The "css" namespace is rendered in the head
right after the base css files, the "js" namespace is rendered at the very
bottom of the body, right after we load jQuery.
Now to our included template. We assume there's a context variable called
``userid`` which will be used with the javascript code.
Your template (``inc.html``) might look like this::
{% load sekizai_tags %}
{% addtoblock "js" %}
{% endaddtoblock %}
{% addtoblock "js" %}
{% endaddtoblock %}
The important thing to notice here is that we split the javascript into two
``addtoblock`` blocks. Like this, the library 'mylib.js' is only included once,
and the userid specific code will be included once per userid.
Now to put it all together let's assume we render a third template with
``[1, 2, 3]`` as ``my_userids`` variable.
The third template looks like this::
{% extends "base.html" %}
{% block "content" %}
{% for userid in my_userids %}
{% include "inc.html" %}
{% endfor %}
{% endblock %}
And here's the rendered template::
Your website
*********
Changelog
*********
0.11.0
======
* Added support for Django 1.11, 2.0, 2.1, and 2.2
* Removed support for Django < 1.11
0.10.0
======
* Added support for Django 1.10
* Removed support for Python 2.6
0.9.0
=====
* Added Changelog
* Added support for Django 1.9
* Added support for Python 3.5
django-sekizai-1.0.0/runtests.py 0000664 0000000 0000000 00000002400 13453626426 0016657 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
import os
import sys
urlpatterns = []
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
}
INSTALLED_APPS = [
'sekizai',
]
ROOT_URLCONF = 'runtests'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(__file__), 'sekizai', 'test_templates')],
'OPTIONS': {
'context_processors': ['sekizai.context_processors.sekizai'],
'debug': True,
},
},
]
def runtests():
from django import setup
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
INSTALLED_APPS=INSTALLED_APPS,
ROOT_URLCONF=ROOT_URLCONF,
DATABASES=DATABASES,
TEST_RUNNER='django.test.runner.DiscoverRunner',
TEMPLATES=TEMPLATES,
)
setup()
# Run the test suite, including the extra validation tests.
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=False, failfast=False)
failures = test_runner.run_tests(INSTALLED_APPS)
return failures
def main():
failures = runtests()
sys.exit(failures)
if __name__ == "__main__":
main()
django-sekizai-1.0.0/sekizai/ 0000775 0000000 0000000 00000000000 13453626426 0016061 5 ustar 00root root 0000000 0000000 django-sekizai-1.0.0/sekizai/__init__.py 0000664 0000000 0000000 00000000026 13453626426 0020170 0 ustar 00root root 0000000 0000000 __version__ = '1.0.0'
django-sekizai-1.0.0/sekizai/context.py 0000664 0000000 0000000 00000000567 13453626426 0020127 0 ustar 00root root 0000000 0000000 from django.template import Context
from sekizai.context_processors import sekizai
class SekizaiContext(Context):
"""
An alternative context to be used instead of RequestContext in places where
no request is available.
"""
def __init__(self, *args, **kwargs):
super(SekizaiContext, self).__init__(*args, **kwargs)
self.update(sekizai())
django-sekizai-1.0.0/sekizai/context_processors.py 0000664 0000000 0000000 00000000506 13453626426 0022402 0 ustar 00root root 0000000 0000000 from collections import defaultdict
from sekizai.data import UniqueSequence
from sekizai.helpers import get_varname
def sekizai(request=None):
"""
Simple context processor which makes sure that the SekizaiDictionary is
available in all templates.
"""
return {get_varname(): defaultdict(UniqueSequence)}
django-sekizai-1.0.0/sekizai/context_processors.pyi 0000664 0000000 0000000 00000000300 13453626426 0022543 0 ustar 00root root 0000000 0000000 from typing import Dict, Union
from django.http import HttpRequest
from sekizai.data import UniqueSequence
def sekizai(request: Union[None, HttpRequest]) -> Dict[str, UniqueSequence]: ...
django-sekizai-1.0.0/sekizai/data.py 0000664 0000000 0000000 00000001266 13453626426 0017351 0 ustar 00root root 0000000 0000000 try:
from collections import MutableSequence
except ImportError:
from backport_collections import MutableSequence
class UniqueSequence(MutableSequence):
def __init__(self):
self.data = []
def __contains__(self, item):
return item in self.data
def __iter__(self):
return iter(self.data)
def __getitem__(self, item):
return self.data[item]
def __setitem__(self, key, value):
self.data[key] = value
def __delitem__(self, key):
del self.data[key]
def __len__(self):
return len(self.data)
def insert(self, index, value):
if value not in self:
self.data.insert(index, value)
django-sekizai-1.0.0/sekizai/helpers.py 0000664 0000000 0000000 00000012403 13453626426 0020075 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
from django.conf import settings
from django.template.base import VariableNode, Variable, Context, Template
from django.template.loader import get_template
from django.template.loader_tags import BlockNode, ExtendsNode
def _get_nodelist(tpl):
if isinstance(tpl, Template):
return tpl.nodelist
else:
return tpl.template.nodelist
def is_variable_extend_node(node):
if hasattr(node, 'parent_name_expr') and node.parent_name_expr:
return True
if hasattr(node, 'parent_name') and hasattr(node.parent_name, 'filters'):
if (node.parent_name.filters or
isinstance(node.parent_name.var, Variable)):
return True
return False
def get_context():
context = Context()
context.template = Template('')
return context
def _extend_blocks(extend_node, blocks):
"""
Extends the dictionary `blocks` with *new* blocks in the parent node
(recursive)
"""
# we don't support variable extensions
if is_variable_extend_node(extend_node):
return
parent = extend_node.get_parent(get_context())
# Search for new blocks
for node in _get_nodelist(parent).get_nodes_by_type(BlockNode):
if node.name not in blocks:
blocks[node.name] = node
else:
# set this node as the super node (for {{ block.super }})
block = blocks[node.name]
seen_supers = []
while (hasattr(block.super, 'nodelist') and
block.super not in seen_supers):
seen_supers.append(block.super)
block = block.super
block.super = node
# search for further ExtendsNodes
for node in _get_nodelist(parent).get_nodes_by_type(ExtendsNode):
_extend_blocks(node, blocks)
break
def _extend_nodelist(extend_node):
"""
Returns a list of namespaces found in the parent template(s) of this
ExtendsNode
"""
# we don't support variable extensions (1.3 way)
if is_variable_extend_node(extend_node):
return []
blocks = extend_node.blocks
_extend_blocks(extend_node, blocks)
found = []
for block in blocks.values():
found += _scan_namespaces(block.nodelist, block)
parent_template = extend_node.get_parent(get_context())
# if this is the topmost template, check for namespaces outside of blocks
if not _get_nodelist(parent_template).get_nodes_by_type(ExtendsNode):
found += _scan_namespaces(
_get_nodelist(parent_template),
None
)
else:
found += _scan_namespaces(
_get_nodelist(parent_template),
extend_node
)
return found
def _scan_namespaces(nodelist, current_block=None):
from sekizai.templatetags.sekizai_tags import RenderBlock
found = []
for node in nodelist:
# check if this is RenderBlock node
if isinstance(node, RenderBlock):
# resolve it's name against a dummy context
found.append(node.kwargs['name'].resolve({}))
found += _scan_namespaces(node.blocks['nodelist'], node)
# handle {% extends ... %} tags if check_inheritance is True
elif isinstance(node, ExtendsNode):
found += _extend_nodelist(node)
# in block nodes we have to scan for super blocks
elif isinstance(node, VariableNode) and current_block:
if node.filter_expression.token == 'block.super':
if hasattr(current_block.super, 'nodelist'):
found += _scan_namespaces(
current_block.super.nodelist,
current_block.super
)
return found
def get_namespaces(template):
compiled_template = get_template(template)
return _scan_namespaces(_get_nodelist(compiled_template))
def validate_template(template, namespaces):
"""
Validates that a template (or it's parents if check_inheritance is True)
contain all given namespaces
"""
if getattr(settings, 'SEKIZAI_IGNORE_VALIDATION', False):
return True
found = get_namespaces(template)
for namespace in namespaces:
if namespace not in found:
return False
return True
def get_varname():
return getattr(settings, 'SEKIZAI_VARNAME', 'SEKIZAI_CONTENT_HOLDER')
class Watcher(object):
"""
Watches a context for changes to the sekizai data, so it can be replayed
later. This is useful for caching.
NOTE: This class assumes you ONLY ADD, NEVER REMOVE data from the context!
"""
def __init__(self, context):
self.context = context
self.frozen = dict(
(key, list(value)) for key, value in self.data.items()
)
@property
def data(self):
return self.context.get(get_varname(), {})
def get_changes(self):
sfrozen = set(self.frozen)
sdata = set(self.data)
new_keys = sfrozen ^ sdata
changes = {}
for key in new_keys:
changes[key] = list(self.data[key])
shared_keys = sfrozen & sdata
for key in shared_keys:
old_set = set(self.frozen[key])
new_values = [
item for item in self.data[key] if item not in old_set
]
changes[key] = new_values
return changes
django-sekizai-1.0.0/sekizai/helpers.pyi 0000664 0000000 0000000 00000001416 13453626426 0020250 0 ustar 00root root 0000000 0000000 from typing import Dict, List, Union
from django.template.base import Template, NodeList, Node, Context
def _get_nodelist(tpl: Template) -> NodeList: ...
def is_variable_extend_node(node: Node) -> bool: ...
def get_context() -> Context: ...
def _extend_blocks(extend_node: Node, blocks: Dict[str, Node]): ...
def _extend_nodelist(extend_node: Node) -> List[str]: ...
def _scan_namespaces(nodelist: NodeList, current_block: Union[None, Node]) -> List[str]: ...
def get_namespaces(template: str) -> List[str]: ...
def validate_template(template: str, namespaces: List[str]) -> bool: ...
def get_varname() -> str: ...
class Watcher:
def __init__(self, context: Context) -> None: ...
@property
def data(self) -> dict: ...
def get_changes(self) -> dict: ...
django-sekizai-1.0.0/sekizai/models.py 0000664 0000000 0000000 00000000000 13453626426 0017704 0 ustar 00root root 0000000 0000000 django-sekizai-1.0.0/sekizai/templatetags/ 0000775 0000000 0000000 00000000000 13453626426 0020553 5 ustar 00root root 0000000 0000000 django-sekizai-1.0.0/sekizai/templatetags/__init__.py 0000664 0000000 0000000 00000000000 13453626426 0022652 0 ustar 00root root 0000000 0000000 django-sekizai-1.0.0/sekizai/templatetags/sekizai_tags.py 0000664 0000000 0000000 00000011076 13453626426 0023607 0 ustar 00root root 0000000 0000000 try:
from importlib import import_module
except ImportError:
from django.utils.importlib import import_module
from classytags.arguments import Argument, Flag
from classytags.core import Tag, Options
from classytags.parser import Parser
from django import template
from django.conf import settings
from sekizai.helpers import get_varname
register = template.Library()
def validate_context(context):
"""
Validates a given context.
Returns True if the context is valid.
Returns False if the context is invalid but the error should be silently
ignored.
Raises a TemplateSyntaxError if the context is invalid and we're in debug
mode.
"""
try:
template_debug = context.template.engine.debug
except AttributeError:
# Get the default engine debug value
template_debug = template.Engine.get_default().debug
if get_varname() in context:
return True
if not template_debug:
return False
raise template.TemplateSyntaxError(
"You must enable the 'sekizai.context_processors.sekizai' template "
"context processor or use 'sekizai.context.SekizaiContext' to "
"render your templates."
)
def import_processor(import_path):
if '.' not in import_path:
raise TypeError("Import paths must contain at least one '.'")
module_name, object_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, object_name)
class SekizaiParser(Parser):
def parse_blocks(self):
super(SekizaiParser, self).parse_blocks()
self.blocks['nodelist'] = self.parser.parse()
class AddtoblockParser(Parser):
def parse_blocks(self):
name = self.kwargs['name'].var.token
self.blocks['nodelist'] = self.parser.parse(
('endaddtoblock', 'endaddtoblock %s' % name)
)
self.parser.delete_first_token()
class SekizaiTag(Tag):
def render(self, context):
if validate_context(context):
return super(SekizaiTag, self).render(context)
return ''
class RenderBlock(Tag):
name = 'render_block'
options = Options(
Argument('name'),
'postprocessor',
Argument('postprocessor', required=False, default=None, resolve=False),
parser_class=SekizaiParser,
)
def render_tag(self, context, name, postprocessor, nodelist):
if not validate_context(context):
return nodelist.render(context)
rendered_contents = nodelist.render(context)
varname = get_varname()
data = '\n'.join(context[varname][name])
if postprocessor:
func = import_processor(postprocessor)
data = func(context, data, name)
return '%s\n%s' % (data, rendered_contents)
register.tag('render_block', RenderBlock)
class AddData(SekizaiTag):
name = 'add_data'
options = Options(
Argument('key'),
Argument('value'),
)
def render_tag(self, context, key, value):
varname = get_varname()
context[varname][key].append(value)
return ''
register.tag('add_data', AddData)
class WithData(SekizaiTag):
name = 'with_data'
options = Options(
Argument('name'),
'as',
Argument('variable', resolve=False),
blocks=[
('end_with_data', 'inner_nodelist'),
],
parser_class=SekizaiParser,
)
def render_tag(self, context, name, variable, inner_nodelist, nodelist):
rendered_contents = nodelist.render(context)
varname = get_varname()
data = context[varname][name]
context.push()
context[variable] = data
inner_contents = inner_nodelist.render(context)
context.pop()
return '%s\n%s' % (inner_contents, rendered_contents)
register.tag('with_data', WithData)
class Addtoblock(SekizaiTag):
name = 'addtoblock'
options = Options(
Argument('name'),
Flag('strip', default=False, true_values=['strip']),
'preprocessor',
Argument('preprocessor', required=False, default=None, resolve=False),
parser_class=AddtoblockParser,
)
def render_tag(self, context, name, strip, preprocessor, nodelist):
rendered_contents = nodelist.render(context)
if strip:
rendered_contents = rendered_contents.strip()
if preprocessor:
func = import_processor(preprocessor)
rendered_contents = func(context, rendered_contents, name)
varname = get_varname()
context[varname][name].append(rendered_contents)
return ""
register.tag('addtoblock', Addtoblock)
django-sekizai-1.0.0/sekizai/templatetags/sekizai_tags.pyi 0000664 0000000 0000000 00000000263 13453626426 0023754 0 ustar 00root root 0000000 0000000 from types import ModuleType
from django.template import Context
def validate_context(context: Context) -> bool: ...
def import_processor(import_path: str) -> ModuleType: ...
django-sekizai-1.0.0/sekizai/test_templates/ 0000775 0000000 0000000 00000000000 13453626426 0021116 5 ustar 00root root 0000000 0000000 django-sekizai-1.0.0/sekizai/test_templates/basic.html 0000664 0000000 0000000 00000000344 13453626426 0023066 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% render_block "css" %}
some content
{% addtoblock "css" %}
my css file
{% endaddtoblock %}
more content
{% addtoblock "js" %}
my js file
{% endaddtoblock %}
final content
{% render_block "js" %}
django-sekizai-1.0.0/sekizai/test_templates/css.html 0000664 0000000 0000000 00000000241 13453626426 0022571 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% render_block "css-to-file" %}
{% addtoblock "css-to-file" %}
{% endaddtoblock %} django-sekizai-1.0.0/sekizai/test_templates/css2.html 0000664 0000000 0000000 00000000404 13453626426 0022654 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% render_block "css-onefile" %}
{% addtoblock "css-onefile" %}{% endaddtoblock %}
{% addtoblock "css-onefile" %}{% endaddtoblock %} django-sekizai-1.0.0/sekizai/test_templates/easy_base.html 0000664 0000000 0000000 00000000130 13453626426 0023731 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% render_block "css" %}
{% block main %}content{% endblock %} django-sekizai-1.0.0/sekizai/test_templates/easy_inherit.html 0000664 0000000 0000000 00000000117 13453626426 0024466 0 ustar 00root root 0000000 0000000 {% extends "easy_base.html" %}
{% block main %}{{ block.super }}{% endblock %} django-sekizai-1.0.0/sekizai/test_templates/eat.html 0000664 0000000 0000000 00000000132 13453626426 0022551 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% addtoblock "css" %}
my css file
{% endaddtoblock %}
mycontent django-sekizai-1.0.0/sekizai/test_templates/errors/ 0000775 0000000 0000000 00000000000 13453626426 0022432 5 ustar 00root root 0000000 0000000 django-sekizai-1.0.0/sekizai/test_templates/errors/failadd.html 0000664 0000000 0000000 00000000106 13453626426 0024701 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% addtoblock %}
file one
{% endaddtoblock %} django-sekizai-1.0.0/sekizai/test_templates/errors/failbase.html 0000664 0000000 0000000 00000000211 13453626426 0025060 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% render_block "js" %}
{% include "errors/failinc.html" %}
{% addtoblock "js" %}
file one
{% endaddtoblock %} django-sekizai-1.0.0/sekizai/test_templates/errors/failbase2.html 0000664 0000000 0000000 00000000211 13453626426 0025142 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% include "errors/failinc.html" %}
{% addtoblock "js" %}
file one
{% endaddtoblock %}
{% render_block "js" %} django-sekizai-1.0.0/sekizai/test_templates/errors/failinc.html 0000664 0000000 0000000 00000000112 13453626426 0024717 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% addtoblock "js %}
file two
{% endaddtoblock %} django-sekizai-1.0.0/sekizai/test_templates/errors/failrender.html 0000664 0000000 0000000 00000000053 13453626426 0025431 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% render_block %} django-sekizai-1.0.0/sekizai/test_templates/inherit/ 0000775 0000000 0000000 00000000000 13453626426 0022560 5 ustar 00root root 0000000 0000000 django-sekizai-1.0.0/sekizai/test_templates/inherit/base.html 0000664 0000000 0000000 00000000520 13453626426 0024355 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
head start
{% render_block "css" %}
head end
include start
{% include "inherit/baseinc.html" %}
include end
block main start
{% block "main" %}
block main base contents
{% endblock %}
block main end
body pre-end
{% render_block "js" %}
body end
{% addtoblock "css" %}
some css file
{% endaddtoblock %} django-sekizai-1.0.0/sekizai/test_templates/inherit/baseinc.html 0000664 0000000 0000000 00000000132 13453626426 0025046 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
inc add js
{% addtoblock "js" %}
inc js file
{% endaddtoblock %} django-sekizai-1.0.0/sekizai/test_templates/inherit/chain.html 0000664 0000000 0000000 00000000151 13453626426 0024525 0 ustar 00root root 0000000 0000000 {% extends "inherit/extend.html" %}
{% block "main" %}
{{ block.super }}
{{ other_var }}
{% endblock %} django-sekizai-1.0.0/sekizai/test_templates/inherit/extend.html 0000664 0000000 0000000 00000000301 13453626426 0024727 0 ustar 00root root 0000000 0000000 {% extends "inherit/base.html" %}
{% load sekizai_tags %}
{% addtoblock "css" %}
invisible css file
{% endaddtoblock %}
{% block "main" %}
{% include "inherit/extinc.html" %}
{% endblock %} django-sekizai-1.0.0/sekizai/test_templates/inherit/extinc.html 0000664 0000000 0000000 00000000040 13453626426 0024732 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
extinc
django-sekizai-1.0.0/sekizai/test_templates/inherit/nullbase.html 0000664 0000000 0000000 00000000000 13453626426 0025241 0 ustar 00root root 0000000 0000000 django-sekizai-1.0.0/sekizai/test_templates/inherit/nullext.html 0000664 0000000 0000000 00000000127 13453626426 0025141 0 ustar 00root root 0000000 0000000 {% extends "inherit/nullbase.html" %}
{% load sekizai_tags %}
{% render_block "js" %} django-sekizai-1.0.0/sekizai/test_templates/inherit/spacechain.html 0000664 0000000 0000000 00000000047 13453626426 0025545 0 ustar 00root root 0000000 0000000 {% extends "inherit/extend.html" %} django-sekizai-1.0.0/sekizai/test_templates/inherit/subvarchain.html 0000664 0000000 0000000 00000000045 13453626426 0025752 0 ustar 00root root 0000000 0000000 {% extends "inherit/varchain.html" %} django-sekizai-1.0.0/sekizai/test_templates/inherit/super_blocks.html 0000664 0000000 0000000 00000000370 13453626426 0026141 0 ustar 00root root 0000000 0000000 {% extends "inherit/base.html" %}
{% load sekizai_tags %}
{% addtoblock "css" %}
invisible css file
{% endaddtoblock %}
{% block "main" %}
{{ block.super }}
{% addtoblock "css" %}
visible css file
{% endaddtoblock %}
more contents
{% endblock %} django-sekizai-1.0.0/sekizai/test_templates/inherit/varchain.html 0000664 0000000 0000000 00000000023 13453626426 0025234 0 ustar 00root root 0000000 0000000 {% extends var %}
django-sekizai-1.0.0/sekizai/test_templates/named_end.html 0000664 0000000 0000000 00000000172 13453626426 0023716 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% addtoblock "myblock" %}
mycontent
{% endaddtoblock "myblock" %}
{% render_block "myblock" %}
django-sekizai-1.0.0/sekizai/test_templates/namespaces.html 0000664 0000000 0000000 00000000370 13453626426 0024123 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% render_block "one" %}
{% render_block "two" %}
{% addtoblock "one" %}
the same file
{% endaddtoblock %}
{% addtoblock "two" %}
the same file
{% endaddtoblock %}
{% addtoblock "one" %}
the same file
{% endaddtoblock %} django-sekizai-1.0.0/sekizai/test_templates/processors/ 0000775 0000000 0000000 00000000000 13453626426 0023320 5 ustar 00root root 0000000 0000000 django-sekizai-1.0.0/sekizai/test_templates/processors/addtoblock_namespace.html 0000664 0000000 0000000 00000000250 13453626426 0030325 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
header
{% addtoblock "js" preprocessor "sekizai.tests.namespace_processor" %}
javascript
{% endaddtoblock %}
footer
{% render_block "js" %}
django-sekizai-1.0.0/sekizai/test_templates/processors/addtoblock_null.html 0000664 0000000 0000000 00000000243 13453626426 0027345 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
header
{% addtoblock "js" preprocessor "sekizai.tests.null_processor" %}
javascript
{% endaddtoblock %}
footer
{% render_block "js" %}
django-sekizai-1.0.0/sekizai/test_templates/processors/namespace.html 0000664 0000000 0000000 00000000251 13453626426 0026140 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
header
{% addtoblock "js" %}
javascript
{% endaddtoblock %}
footer
{% render_block "js" postprocessor "sekizai.tests.namespace_processor" %}
django-sekizai-1.0.0/sekizai/test_templates/processors/null.html 0000664 0000000 0000000 00000000244 13453626426 0025160 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
header
{% addtoblock "js" %}
javascript
{% endaddtoblock %}
footer
{% render_block "js" postprocessor "sekizai.tests.null_processor" %}
django-sekizai-1.0.0/sekizai/test_templates/unique.html 0000664 0000000 0000000 00000000246 13453626426 0023314 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% render_block "unique" %}
{% addtoblock "unique" %}unique data{% endaddtoblock %}
{% addtoblock "unique" %}unique data{% endaddtoblock %}
django-sekizai-1.0.0/sekizai/test_templates/variables.html 0000664 0000000 0000000 00000000373 13453626426 0023757 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% addtoblock blockname %}
file two
{% endaddtoblock %}
{% addtoblock "one" %}
file two
{% endaddtoblock %}
{% addtoblock blockname|upper %}
file one
{% endaddtoblock %}
{% render_block "ONE" %}
{% render_block blockname %} django-sekizai-1.0.0/sekizai/test_templates/with_data.html 0000664 0000000 0000000 00000000251 13453626426 0023746 0 ustar 00root root 0000000 0000000 {% load sekizai_tags %}
{% with_data "key" as mylist %}
{% for obj in mylist %}
{{ obj }}
{% endfor %}
{% end_with_data %}
{% add_data "key" 1 %}
{% add_data "key" 2 %} django-sekizai-1.0.0/sekizai/tests.py 0000664 0000000 0000000 00000034756 13453626426 0017614 0 ustar 00root root 0000000 0000000 from __future__ import with_statement
from difflib import SequenceMatcher
import os
from unittest import TestCase
import sys
import django
from django import template
from django.conf import settings
from django.template.loader import render_to_string
from django.template.engine import Engine
import pep8
from sekizai import context_processors
from sekizai.context import SekizaiContext
from sekizai.helpers import get_namespaces
from sekizai.helpers import get_varname
from sekizai.helpers import validate_template
from sekizai.helpers import Watcher
from sekizai.templatetags.sekizai_tags import import_processor
from sekizai.templatetags.sekizai_tags import validate_context
try:
unicode_compat = unicode
except NameError:
unicode_compat = str
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
def null_processor(context, data, namespace):
return ''
def namespace_processor(context, data, namespace):
return namespace
class SettingsOverride(object):
"""
Overrides Django settings within a context and resets them to their initial
values on exit.
Example:
with SettingsOverride(DEBUG=True):
# do something
"""
class NULL:
pass
def __init__(self, **overrides):
self.overrides = overrides
def __enter__(self):
self.old = {}
for key, value in self.overrides.items():
self.old[key] = getattr(settings, key, self.NULL)
setattr(settings, key, value)
def __exit__(self, type, value, traceback):
for key, value in self.old.items():
if value is self.NULL:
delattr(settings, key)
else:
setattr(settings, key, value)
class CaptureStdout(object):
"""
Overrides sys.stdout with a StringIO stream.
"""
def __init__(self):
self.old = None
def __enter__(self):
self.old = sys.stdout
new = sys.stdout = StringIO()
return new
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self.old
class Match(tuple): # pragma: no cover
@property
def a(self):
return self[0]
@property
def b(self):
return self[1]
@property
def size(self):
return self[2]
def _backwards_compat_match(thing): # pragma: no cover
if isinstance(thing, tuple):
return Match(thing)
return thing
class BitDiffResult(object):
def __init__(self, status, message):
self.status = status
self.message = message
class BitDiff(object):
"""
Visual aid for failing tests
"""
def __init__(self, expected):
self.expected = [repr(unicode_compat(bit)) for bit in expected]
def test(self, result):
result = [repr(unicode_compat(bit)) for bit in result]
if self.expected == result:
return BitDiffResult(True, "success")
else: # pragma: no cover
longest = max(
[len(x) for x in self.expected] +
[len(x) for x in result] +
[len('Expected')]
)
sm = SequenceMatcher()
sm.set_seqs(self.expected, result)
matches = sm.get_matching_blocks()
lasta = 0
lastb = 0
data = []
for match in [_backwards_compat_match(match) for match in matches]:
unmatcheda = self.expected[lasta:match.a]
unmatchedb = result[lastb:match.b]
unmatchedlen = max([len(unmatcheda), len(unmatchedb)])
unmatcheda += ['' for x in range(unmatchedlen)]
unmatchedb += ['' for x in range(unmatchedlen)]
for i in range(unmatchedlen):
data.append((False, unmatcheda[i], unmatchedb[i]))
for i in range(match.size):
data.append((
True, self.expected[match.a + i], result[match.b + i]
))
lasta = match.a + match.size
lastb = match.b + match.size
padlen = (longest - len('Expected'))
padding = ' ' * padlen
line1 = '-' * padlen
line2 = '-' * (longest - len('Result'))
msg = '\nExpected%s | | Result' % padding
msg += '\n--------%s-|---|-------%s' % (line1, line2)
for success, a, b in data:
pad = ' ' * (longest - len(a))
if success:
msg += '\n%s%s | | %s' % (a, pad, b)
else:
msg += '\n%s%s | ! | %s' % (a, pad, b)
return BitDiffResult(False, msg)
def update_template_debug(debug=True):
"""
Helper method for updating the template debug option based on
the django version. Use the results of this function as the context.
:return: SettingsOverride object
"""
# Create our overridden template settings with debug turned off.
templates_override = settings.TEMPLATES
templates_override[0]['OPTIONS'].update({'debug': debug})
# Engine gets created based on template settings initial value so
# changing the settings after the fact won't update, so do it
# manually. Necessary when testing validate_context
# with render method and want debug off.
Engine.get_default().debug = debug
return SettingsOverride(TEMPLATES=templates_override)
class SekizaiTestCase(TestCase):
def _render(self, tpl, ctx=None, sekizai_context=True):
ctx = dict(ctx) if ctx else {}
if sekizai_context:
ctx.update(context_processors.sekizai())
return render_to_string(tpl, ctx)
def _get_bits(self, tpl, ctx=None, sekizai_context=True):
ctx = ctx or {}
rendered = self._render(tpl, ctx, sekizai_context)
bits = [
bit for bit in [bit.strip('\n')
for bit in rendered.split('\n')] if bit
]
return bits, rendered
def _test(self, tpl, res, ctx=None, sekizai_context=True):
"""
Helper method to render template and compare it's bits
"""
ctx = ctx or {}
bits, rendered = self._get_bits(tpl, ctx, sekizai_context)
differ = BitDiff(res)
result = differ.test(bits)
self.assertTrue(result.status, result.message)
return rendered
def test_pep8(self):
sekizai_dir = os.path.dirname(os.path.abspath(__file__))
pep8style = pep8.StyleGuide()
with CaptureStdout() as stdout:
result = pep8style.check_files([sekizai_dir])
errors = stdout.getvalue()
self.assertEqual(
result.total_errors, 0,
"Code not PEP8 compliant:\n{0}".format(errors)
)
def test_basic_dual_block(self):
"""
Basic dual block testing
"""
bits = [
'my css file', 'some content', 'more content', 'final content',
'my js file'
]
self._test('basic.html', bits)
def test_named_endaddtoblock(self):
"""
Testing with named endaddblock
"""
bits = ["mycontent"]
self._test('named_end.html', bits)
def test_eat_content_before_render_block(self):
"""
Testing that content gets eaten if no render_blocks is available
"""
bits = ["mycontent"]
self._test("eat.html", bits)
def test_sekizai_context_required(self):
"""
Test that the template tags properly fail if not used with either
SekizaiContext or the context processor.
"""
with self.assertRaises(template.TemplateSyntaxError):
self._render('basic.html', {}, sekizai_context=False)
def test_complex_template_inheritance(self):
"""
Test that (complex) template inheritances work properly
"""
bits = [
"head start",
"some css file",
"head end",
"include start",
"inc add js",
"include end",
"block main start",
"extinc",
"block main end",
"body pre-end",
"inc js file",
"body end"
]
self._test("inherit/extend.html", bits)
"""
Test that blocks (and block.super) work properly with sekizai
"""
bits = [
"head start",
"visible css file",
"some css file",
"head end",
"include start",
"inc add js",
"include end",
"block main start",
"block main base contents",
"more contents",
"block main end",
"body pre-end",
"inc js file",
"body end"
]
self._test("inherit/super_blocks.html", bits)
def test_namespace_isolation(self):
"""
Tests that namespace isolation works
"""
bits = ["the same file", "the same file"]
self._test('namespaces.html', bits)
def test_variable_namespaces(self):
"""
Tests variables and filtered variables as block names.
"""
bits = ["file one", "file two"]
self._test('variables.html', bits, {'blockname': 'one'})
def test_invalid_addtoblock(self):
"""
Tests that template syntax errors are raised properly in templates
rendered by sekizai tags
"""
self.assertRaises(
template.TemplateSyntaxError,
self._render, 'errors/failadd.html'
)
def test_invalid_renderblock(self):
self.assertRaises(
template.TemplateSyntaxError,
self._render, 'errors/failrender.html'
)
def test_invalid_include(self):
self.assertRaises(
template.TemplateSyntaxError,
self._render, 'errors/failinc.html'
)
def test_invalid_basetemplate(self):
self.assertRaises(
template.TemplateSyntaxError,
self._render, 'errors/failbase.html'
)
def test_invalid_basetemplate_two(self):
self.assertRaises(
template.TemplateSyntaxError,
self._render, 'errors/failbase2.html'
)
def test_with_data(self):
"""
Tests the with_data/add_data tags.
"""
bits = ["1", "2"]
self._test('with_data.html', bits)
def test_easy_inheritance(self):
self.assertEqual('content', self._render("easy_inherit.html").strip())
def test_validate_context(self):
sekizai_ctx = SekizaiContext()
django_ctx = template.Context()
self.assertRaises(
template.TemplateSyntaxError,
validate_context, django_ctx
)
self.assertEqual(validate_context(sekizai_ctx), True)
with update_template_debug(debug=False):
self.assertEqual(validate_context(django_ctx), False)
self.assertEqual(validate_context(sekizai_ctx), True)
bits = ['some content', 'more content', 'final content']
self._test('basic.html', bits, sekizai_context=False)
def test_post_processor_null(self):
bits = ['header', 'footer']
self._test('processors/null.html', bits)
def test_post_processor_namespace(self):
bits = ['header', 'footer', 'js']
self._test('processors/namespace.html', bits)
def test_import_processor_failfast(self):
self.assertRaises(TypeError, import_processor, 'invalidpath')
def test_unique(self):
bits = ['unique data']
self._test('unique.html', bits)
def test_strip(self):
tpl = template.Template("""
{% load sekizai_tags %}
{% addtoblock 'a' strip %} test{% endaddtoblock %}
{% addtoblock 'a' strip %}test {% endaddtoblock %}
{% render_block 'a' %}""")
context = SekizaiContext()
output = tpl.render(context)
self.assertEqual(output.count('test'), 1, output)
def test_addtoblock_processor_null(self):
bits = ['header', 'footer']
self._test('processors/addtoblock_null.html', bits)
def test_addtoblock_processor_namespace(self):
bits = ['header', 'footer', 'js']
self._test('processors/addtoblock_namespace.html', bits)
class HelperTests(TestCase):
def test_validate_template_js_css(self):
self.assertTrue(validate_template('basic.html', ['js', 'css']))
def test_validate_template_js(self):
self.assertTrue(validate_template('basic.html', ['js']))
def test_validate_template_css(self):
self.assertTrue(validate_template('basic.html', ['css']))
def test_validate_template_empty(self):
self.assertTrue(validate_template('basic.html', []))
def test_validate_template_notfound(self):
self.assertFalse(validate_template('basic.html', ['notfound']))
def test_get_namespaces_easy_inherit(self):
self.assertEqual(get_namespaces('easy_inherit.html'), ['css'])
def test_get_namespaces_chain_inherit(self):
self.assertEqual(get_namespaces('inherit/chain.html'), ['css', 'js'])
def test_get_namespaces_space_chain_inherit(self):
self.assertEqual(
get_namespaces('inherit/spacechain.html'),
['css', 'js']
)
def test_get_namespaces_var_inherit(self):
self.assertEqual(get_namespaces('inherit/varchain.html'), [])
def test_get_namespaces_sub_var_inherit(self):
self.assertEqual(get_namespaces('inherit/subvarchain.html'), [])
def test_get_namespaces_null_ext(self):
self.assertEqual(get_namespaces('inherit/nullext.html'), [])
def test_deactivate_validate_template(self):
with SettingsOverride(SEKIZAI_IGNORE_VALIDATION=True):
self.assertTrue(validate_template('basic.html', ['js', 'css']))
self.assertTrue(validate_template('basic.html', ['js']))
self.assertTrue(validate_template('basic.html', ['css']))
self.assertTrue(validate_template('basic.html', []))
self.assertTrue(validate_template('basic.html', ['notfound']))
def test_watcher_add_namespace(self):
context = SekizaiContext()
watcher = Watcher(context)
varname = get_varname()
context[varname]['key'].append('value')
changes = watcher.get_changes()
self.assertEqual(changes, {'key': ['value']})
def test_watcher_add_data(self):
context = SekizaiContext()
varname = get_varname()
context[varname]['key'].append('value')
watcher = Watcher(context)
context[varname]['key'].append('value2')
changes = watcher.get_changes()
self.assertEqual(changes, {'key': ['value2']})
django-sekizai-1.0.0/setup.cfg 0000664 0000000 0000000 00000000032 13453626426 0016236 0 ustar 00root root 0000000 0000000 [bdist_wheel]
universal=1
django-sekizai-1.0.0/setup.py 0000664 0000000 0000000 00000002321 13453626426 0016132 0 ustar 00root root 0000000 0000000 from setuptools import setup, find_packages
version = __import__('sekizai').__version__
setup(
name='django-sekizai',
version=version,
description='Django Sekizai',
author='Jonas Obrist',
author_email='ojiidotch@gmail.com',
url='http://github.com/ojii/django-sekizai',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
install_requires=[
'django>=1.11',
'django-classy-tags>=0.3.1',
],
test_suite='runtests.main',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Framework :: Django :: 2.1',
'Framework :: Django :: 2.2',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
]
)