Skip to content
Snippets Groups Projects
Commit 64e9a9e4 authored by martin-corredera's avatar martin-corredera
Browse files

Adding plugins

parent 7b437ead
Branches
No related tags found
No related merge requests found
Pipeline #49160 passed
Showing
with 1795 additions and 0 deletions
*~
._*
.*.swp
.*.swo
*.pyc
*.log
.DS_Store
.directory
.idea
.project
.pydevproject
__pycache__
.vscode
[submodule "pelican-fontawesome"]
path = pelican-fontawesome
url = https://github.com/kura/pelican-fontawesome.git
[submodule "pelican_youtube"]
path = pelican_youtube
url = https://github.com/kura/pelican_youtube.git
[submodule "pelican_vimeo"]
path = pelican_vimeo
url = https://github.com/kura/pelican_vimeo.git
[submodule "cjk-auto-spacing"]
path = cjk-auto-spacing
url = https://github.com/yuex/cjk-auto-spacing.git
[submodule "pelican-gist"]
path = pelican-gist
url = https://github.com/streeter/pelican-gist.git
[submodule "pelicanfly"]
path = pelicanfly
url = https://github.com/bmcorser/pelicanfly.git
[submodule "pelican-flickr"]
path = pelican-flickr
url = https://github.com/La0/pelican-flickr.git
[submodule "better_code_samples"]
path = better_code_samples
url = https://github.com/ChrislS/better_code_samples.git
[submodule "pin_to_top"]
path = pin_to_top
url = https://github.com/Shaked/pin_to_top.git
[submodule "pelican-githubprojects"]
path = pelican-githubprojects
url = https://github.com/kura/pelican-githubprojects.git
[submodule "pelicanthemes-generator"]
path = pelicanthemes-generator
url = https://github.com/badele/pelicanthemes-generator
[submodule "pelican-page-order"]
path = pelican-page-order
url = https://github.com/akhayyat/pelican-page-order.git
[submodule "pelican-page-hierarchy"]
path = pelican-page-hierarchy
url = https://github.com/akhayyat/pelican-page-hierarchy.git
[submodule "multi_neighbors"]
path = multi_neighbors
url = https://github.com/davidlesieur/multi_neighbors.git
[submodule "pelican-langcategory"]
path = pelican-langcategory
url = https://github.com/CNBorn/pelican-langcategory.git
[submodule "pandoc_reader"]
path = pandoc_reader
url = https://github.com/liob/pandoc_reader.git
[submodule "bootstrapify"]
path = bootstrapify
url = https://github.com/ingwinlu/pelican-bootstrapify.git
[submodule "pelican-jinja2content"]
path = pelican-jinja2content
url = https://github.com/joachimneu/pelican-jinja2content.git
[submodule "panorama"]
path = panorama
url = https://github.com/romainx/panorama.git
[submodule "pelican-genealogy"]
path = pelican-genealogy
url = https://github.com/zappala/pelican-genealogy
[submodule "image_process"]
path = image_process
url = https://github.com/whiskyechobravo/image_process
[submodule "pelican-open_graph"]
path = pelican-open_graph
url = https://github.com/whiskyechobravo/pelican-open_graph.git
[submodule "replacer"]
path = replacer
url = https://github.com/narusemotoki/replacer
[submodule "pelican-toc"]
path = pelican-toc
url = https://github.com/ingwinlu/pelican-toc
[submodule "multimarkdown_reader"]
path = multimarkdown_reader
url = https://github.com/dames57/multimarkdown_reader.git
[submodule "pelican_javascript"]
path = pelican_javascript
url = https://github.com/mortada/pelican_javascript.git
[submodule "loadcsv"]
path = loadcsv
url = https://github.com/e9t/pelican-loadcsv
[submodule "org_pandoc_reader"]
path = org_pandoc_reader
url = https://github.com/jo-tham/org_pandoc_reader.git
[submodule "pdf-img"]
path = pdf-img
url = https://github.com/cmacmackin/pdf-img.git
[submodule "pelican-cite"]
path = pelican-cite
url = https://github.com/cmacmackin/pelican-cite.git
[submodule "figure-ref"]
path = figure-ref
url = https://github.com/cmacmackin/figure-ref
[submodule "encrypt-content"]
path = encrypt-content
url = https://github.com/mindcruzer/pelican-encrypt-content
[submodule "md-metayaml"]
path = md-metayaml
url = https://github.com/joachimneu/pelican-md-metayaml
[submodule "backreftranslate"]
path = backreftranslate
url = https://github.com/daltonmatos/pelican-plugin-backref-translate
[submodule "category_order"]
path = category_order
url = https://github.com/jhshi/pelican.plugins.category_order.git
[submodule "ga_page_view"]
path = ga_page_view
url = https://github.com/jhshi/pelican.plugins.ga_page_view.git
[submodule "post_revision"]
path = post_revision
url = https://github.com/jhshi/pelican.plugins.post_revision
[submodule "linkclass"]
path = pelican-linkclass
url = https://github.com/rlaboiss/pelican-linkclass
[submodule "just_table"]
path = just_table
url = https://github.com/burakkose/just_table
[submodule "ace_editor"]
path = ace_editor
url = https://github.com/mothsART/ace_editor.git
[submodule "mboxreader"]
path = pelican-mboxreader
url = https://github.com/TC01/pelican-mboxreader
[submodule "pelican-version"]
path = pelican-version
url = https://github.com/Shaked/pelican-version
[submodule "lightbox"]
path = lightbox
url = https://github.com/kura/lightbox
[submodule "pelican-ipynb"]
path = pelican-ipynb
url = https://github.com/danielfrg/pelican-ipynb
[submodule "deadlinks"]
path = deadlinks
url = https://github.com/silentlamb/pelican-deadlinks.git
[submodule "pelican-ert"]
path = pelican-ert
url = https://github.com/nogaems/pelican-ert.git
[submodule "pelican_meetup_info"]
path = pelican_meetup_info
url = https://github.com/tylerdave/pelican-meetup-info.git
[submodule "similar_posts"]
path = similar_posts
url = https://github.com/davidlesieur/similar_posts.git
language: python
python:
- "3.7"
cache: pip
env:
- R_LIBS_USER=$TRAVIS_BUILD_DIR/R/Library
cache:
directories:
- $R_LIBS_USER
before_install:
# By default R 3.2.3 is installed with xenial, but rpy2 requires R >= 3.3
# Hence we add an extra deb package repo to get a more recent version:
- sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
- sudo add-apt-repository 'deb [arch=amd64,i386] https://cloud.r-project.org/bin/linux/ubuntu xenial/'
- sudo apt-get update -qq
- sudo apt-get install -qq --no-install-recommends asciidoctor pandoc plantuml r-base ruby-sass
- mkdir -p $R_LIBS_USER
- echo 'install.packages("knitr", repos="https://cran.rstudio.com")' | R --no-save
install:
- pip install -U -r requirements.txt
# Installing pelican in editable mode makes its tests.support package available to us
- pip install -e git+https://github.com/getpelican/pelican.git#egg=pelican
# The following commands install all plugins dependencies.
# The `grep` & `sed commands` below are needed because some submodules have conflicting requirements.
# cf. https://github.com/getpelican/pelican-plugins/issues/1170
- pip install -U -r <(grep -hv pelican */requirements.txt | sed 's/==/>=/')
# We need to exclude the multimarkdown_reader & pandoc_reader plugins,
# otherwise their BaseReader subclasses will be loaded by pelican.readers.Readers,
# and override the default .md one.
# We also need to exclude the image_process plugin as long as they are not fixed, cf. https://github.com/getpelican/pelican-plugins/issues/1170
script: nosetests --with-summary-report
--exclude-dir=multimarkdown_reader --exclude-dir=pandoc_reader
--exclude-dir=image_process
Contributing a plugin
=====================
Details regarding how to write a plugin are explained in the Pelican `docs`_.
If you want to contribute, **please be sure** to read our general contributing
`guidelines`_ first. Then you can fork this repository, create a new branch,
make your changes, squash your commits, and issue your pull request from your
new branch (i.e., **not** the ``master`` branch).
Make sure that your plugin follows the structure below::
my_plugin
├── __init__.py
├── my_plugin.py
├── test_my_plugin.py
└── ReadMe.rst / ReadMe.md
``my_plugin.py`` is the actual plugin implementation. Include a brief
explanation of what the plugin does as a module docstring. Put any further
explanations and usage details into the ``ReadMe`` file.
``__init__.py`` should contain a single line with ``from .my_plugin import *``.
Place tests for your plugin in the same folder inside ``test_my_plugin.py``.
If you need content or templates in your tests, you can use the main
``test_data`` folder for that purpose.
**Note:** Each plugin can contain a LICENSE file stating the license it's
released under. If there is an absence of LICENSE then it defaults to the
*GNU AFFERO GENERAL PUBLIC LICENSE Version 3*. Please refer to the ``LICENSE``
file for the full text of the license.
Before making your initial commit, please be sure to add an entry to the repo's
top-level ``ReadMe`` file, adding your plugin to the list (in alphabetical
order) and providing a brief description.
.. _guidelines: http://docs.getpelican.com/en/latest/contribute.html#using-git-and-github
.. _docs: http://docs.getpelican.com/en/latest/plugins.html#how-to-create-plugins
This diff is collapsed.
# Pelican on GitLab Pages
Example [Pelican] website using GitLab Pages. Check the resulting website here: <https://pages.gitlab.io/pelican>
Learn more about [GitLab Pages](https://about.gitlab.com/stages-devops-lifecycle/pages/) and the [official
documentation](https://docs.gitlab.com/ce/user/project/pages/), including
[how to fork a project like this one to get started](https://docs.gitlab.com/ee/user/project/pages/getting_started_part_two.html#fork-a-project-to-get-started-from).
---
## GitLab CI
This project's static Pages are built by [GitLab CI][ci], following the steps
defined in the file [`.gitlab-ci.yml`](.gitlab-ci.yml).
## Building locally
To work locally with this project, you'll have to follow the steps below:
1. Fork, clone or download this project
1. [Install][] Pelican
1. Regenerate and serve on port 8000: `make devserver`
1. Add content
Read more at Pelican's [documentation].
## GitLab User or Group Pages
To use this project as your user/group website, you will need to perform
some additional steps:
1. Rename your project to `namespace.gitlab.io`, where `namespace` is
your `username` or `groupname`. This can be done by navigating to your
project's **Settings > General (Advanced)**.
2. Adjust Pelican's `SITEURL` configuration setting in `publishconf.py` to
the new URL (e.g. `https://namespace.gitlab.io`)
Read more about [GitLab Pages for projects and user/group websites][pagesdoc].
## Use a custom theme
To use a custom theme:
1. Visit <https://github.com/getpelican/pelican-themes> and pick the name of
the theme you want to use.
1. Uncomment the following lines from `.gitlab-ci.yml`, replacing `<theme_name>`
with the name of the theme you chose:
```yaml
- svn export https://github.com/getpelican/pelican-themes/trunk/<theme-name> /tmp/<theme-name>
- pelican-themes --install /tmp/<theme-name>
```
1. Edit `pelicanconf.py` and add the theme:
```plaintext
THEME = '/tmp/<theme-name>'
```
For more information, see the discussion in [issue #1](https://gitlab.com/pages/pelican/-/issues/1).
## Did you fork this project?
If you forked this project for your own use, please go to your project's
**Settings** and remove the forking relationship, which won't be necessary
unless you want to contribute back to the upstream project.
## Troubleshooting
1. CSS is missing! That means two things:
Either that you have wrongly set up the CSS URL in your templates, or
your static generator has a configuration option that needs to be explicitly
set in order to serve static assets under a relative URL.
[ci]: https://about.gitlab.com/gitlab-ci/
[pelican]: http://blog.getpelican.com/
[install]: https://docs.getpelican.com/en/stable/install.html
[documentation]: http://docs.getpelican.com/
[pagesdoc]: https://docs.gitlab.com/ce/user/project/pages/getting_started_part_one.html
This diff is collapsed.
# Always Modified
Say you want to sort by modified date/time in a theme template, but not all
your articles have modified date/timestamps explicitly defined in article
metadata. This plugin facilitates that sorting by assuming the modified date
(if undefined) is equal to the created date.
## Usage
1. Add `ALWAYS_MODIFIED = True` to your settings file.
2. Now you can sort by modified date in your templates:
{% for article in articles|sort(reverse=True,attribute='modified') %}
from .always_modified import *
"""
If "modified" date/time is not defined in article metadata, fall back to the "created" date.
"""
from pelican import signals
from pelican.contents import Content, Article
def add_modified(content):
if not isinstance(content, Article):
return
if not content.settings.get('ALWAYS_MODIFIED', False):
return
if hasattr(content, 'date') and not hasattr(content, 'modified'):
content.modified = content.date
content.locale_modified = content.locale_date
def register():
signals.content_object_init.connect(add_modified)
AsciiDoc Reader
###############
This plugin allows you to use `AsciiDoc <http://www.methods.co.nz/asciidoc/>`_
to write your posts. File extension should be ``.asc``, ``.adoc``,
or ``.asciidoc``.
Dependency
----------
There are two command line utilities commonly used to render AsciiDoc:
``asciidoc`` and ``asciidoctor``. One of the two will need to be installed and
on the PATH.
**Note**: The ``asciidoctor`` utility is recommended since the original
``asciidoc`` is no longer maintained.
Settings
--------
======================================== =======================================================
Setting name (followed by default value) What does it do?
======================================== =======================================================
``ASCIIDOC_CMD = 'asciidoc'`` Selects which utility to use for rendering. Will
autodetect utility if not provided.
``ASCIIDOC_OPTIONS = []`` A list of options to pass to AsciiDoc. See the `manpage
<http://www.methods.co.nz/asciidoc/manpage.html>`_.
======================================== =======================================================
Example file header
-------------------
Following the `example <https://github.com/getpelican/pelican/blob/master/docs/content.rst#file-metadata>`_ in the main pelican documentation:
.. code-block:: none
= My super title
:date: 2010-10-03 10:20
:modified: 2010-10-04 18:40
:tags: thats, awesome
:category: yeah
:slug: my-super-post
:authors: Alexis Metaireau, Conan Doyle
:summary: Short version for index and feeds
== title level 2
and so on...
from .asciidoc_reader import *
# -*- coding: utf-8 -*-
"""
AsciiDoc Reader
===============
This plugin allows you to use AsciiDoc to write your posts.
File extension should be ``.asc``, ``.adoc``, or ``asciidoc``.
"""
from pelican.readers import BaseReader
from pelican import signals
import os
import re
import subprocess
import sys
import tempfile
import logging
logger = logging.getLogger(__name__)
def encoding():
"""Return encoding used to decode shell output in call function"""
if os.name == 'nt':
from ctypes import cdll
return 'cp' + str(cdll.kernel32.GetOEMCP())
return 'utf-8'
def call(cmd):
"""Calls a CLI command and returns the stdout as string."""
logger.debug('AsciiDocReader: Running: %s', cmd)
stdoutdata, stderrdata = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate()
if stderrdata:
logger.warning('AsciiDocReader: strderr: %s', stderrdata)
return stdoutdata.decode(encoding())
def default():
"""Attempt to find the default AsciiDoc utility."""
for cmd in ALLOWED_CMDS:
if len(call(cmd + " --help")):
logger.debug('AsciiDocReader: Using cmd: %s', cmd)
return cmd
ALLOWED_CMDS = ["asciidoc", "asciidoctor"]
ENABLED = None != default()
class AsciiDocReader(BaseReader):
"""Reader for AsciiDoc files."""
enabled = ENABLED
file_extensions = ['asc', 'adoc', 'asciidoc']
default_options = ['--no-header-footer']
def read(self, source_path):
"""Parse content and metadata of AsciiDoc files."""
cmd = self._get_cmd()
content = ""
if cmd:
logger.debug('AsciiDocReader: Reading: %s', source_path)
optlist = self.settings.get('ASCIIDOC_OPTIONS', []) + self.default_options
options = " ".join(optlist)
# Beware! # Don't use tempfile.NamedTemporaryFile under Windows: https://bugs.python.org/issue14243
# Also, use mkstemp correctly (Linux and Windows): https://www.logilab.org/blogentry/17873
fd, temp_name = tempfile.mkstemp()
content = call("%s %s -o %s \"%s\"" % (cmd, options, temp_name, source_path))
with open(temp_name, encoding='utf-8') as f:
content = f.read()
os.close(fd)
os.unlink(temp_name)
metadata = self._read_metadata(source_path)
logger.debug('AsciiDocReader: Got content (showing first 50 chars): %s', (content[:50] + '...') if len(content) > 50 else content)
return content, metadata
def _get_cmd(self):
"""Returns the AsciiDoc utility command to use for rendering or None if
one cannot be found."""
if self.settings.get('ASCIIDOC_CMD') in ALLOWED_CMDS:
return self.settings.get('ASCIIDOC_CMD')
return default()
def _read_metadata(self, source_path):
"""Parses the AsciiDoc file at the given `source_path` and returns found
metadata."""
metadata = {}
with open(source_path, encoding='utf-8') as fi:
prev = ""
for line in fi.readlines():
# Parse for doc title.
if 'title' not in metadata.keys():
title = ""
if line.startswith("= "):
title = line[2:].strip()
elif line.count("=") == len(prev.strip()):
title = prev.strip()
if title:
metadata['title'] = self.process_metadata('title', title)
# Parse for other metadata.
regexp = re.compile(r"^:\w+:")
if regexp.search(line):
toks = line.split(":", 2)
key = toks[1].strip().lower()
val = toks[2].strip()
metadata[key] = self.process_metadata(key, val)
prev = line
logger.debug('AsciiDocReader: Found metadata: %s', metadata)
return metadata
def add_reader(readers):
for ext in AsciiDocReader.file_extensions:
readers.reader_classes[ext] = AsciiDocReader
def register():
signals.readers_init.connect(add_reader)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import os
from pelican.readers import Readers
from pelican.tests.support import unittest, get_settings
from .asciidoc_reader import ENABLED
CUR_DIR = os.path.dirname(__file__)
CONTENT_PATH = os.path.join(CUR_DIR, 'test_data')
@unittest.skipUnless(ENABLED, "asciidoc isn't installed")
class AsciiDocReaderTest(unittest.TestCase):
def read_file(self, path, **kwargs):
# Isolate from future API changes to readers.read_file
r = Readers(settings=get_settings(**kwargs))
return r.read_file(base_path=CONTENT_PATH, path=path)
def test_article_with_asc_extension(self):
# Ensure the asc extension is being processed by the correct reader
page = self.read_file(
path='article_with_asc_extension.asc')
expected = ('<div class="sect1">'
'<h2 id="_used_for_pelican_test">'
'Used for pelican test</h2>'
'<div class="sectionbody">'
'<div class="paragraph">'
'<p>The quick brown fox jumped over '
'the lazy dog&#8217;s back.</p>'
'</div></div></div>')
actual = "".join(page.content.splitlines())
expected = "".join(expected.splitlines())
self.assertEqual(actual, expected)
expected = {
'category': 'Blog',
'author': 'Author O. Article',
'title': 'Test AsciiDoc File Header',
'date': datetime.datetime(2011, 9, 15, 9, 5),
'tags': ['Linux', 'Python', 'Pelican'],
}
for key, value in expected.items():
self.assertEqual(value, page.metadata[key], (
'Metadata attribute \'%s\' does not match expected value.\n'
'Expected: %s\n'
'Actual: %s') % (key, value, page.metadata[key]))
def test_article_with_asc_options(self):
# test to ensure the ASCIIDOC_OPTIONS is being used
page = self.read_file(path='article_with_asc_options.asc',
ASCIIDOC_OPTIONS=["-a revision=1.0.42"])
expected = ('<div class="sect1">'
'<h2 id="_used_for_pelican_test">'
'Used for pelican test</h2>'
'<div class="sectionbody">'
'<div class="paragraph">'
'<p>version 1.0.42</p></div>'
'<div class="paragraph">'
'<p>The quick brown fox jumped over '
'the lazy dog&#8217;s back.</p>'
'</div></div></div>')
actual = "".join(page.content.splitlines())
expected = "".join(expected.splitlines())
self.assertEqual(actual, expected)
if __name__ == '__main__':
unittest.main()
Test AsciiDoc File Header
=========================
:Author: Author O. Article
:Email: <author@nowhere.com>
:Date: 2011-09-15 09:05
:Category: Blog
:Tags: Linux, Python, Pelican
== Used for pelican test
The quick brown fox jumped over the lazy dog's back.
= Test AsciiDoc File Header
== Used for pelican test
version {revision}
The quick brown fox jumped over the lazy dog's back.
Asset management
----------------
**NOTE:** `This plugin has been moved to its own repository <https://github.com/pelican-plugins/webassets>`_. Please file any issues/PRs there. Once all plugins have been migrated to the `new Pelican Plugins organization <https://github.com/pelican-plugins>`_, this monolithic repository will be archived.
This plugin allows you to use the `Webassets`_ module to manage assets such as
CSS and JS files. The module must first be installed::
pip install webassets
The Webassets module allows you to perform a number of useful asset management
functions, including:
* CSS minifier (``cssmin``, ``yui_css``, ...)
* CSS compiler (``less``, ``sass``, ...)
* JS minifier (``uglifyjs``, ``yui_js``, ``closure``, ...)
Others filters include CSS URL rewriting, integration of images in CSS via data
URIs, and more. Webassets can also append a version identifier to your asset
URL to convince browsers to download new versions of your assets when you use
far-future expires headers. Please refer to the `Webassets documentation`_ for
more information.
When used with Pelican, Webassets is configured to process assets in the
``OUTPUT_PATH/theme`` directory. You can use Webassets in your templates by
including one or more template tags. The Jinja variable ``{{ ASSET_URL }}`` can
be used in templates and is relative to the ``theme/`` url. The
``{{ ASSET_URL }}`` variable should be used in conjunction with the
``{{ SITEURL }}`` variable in order to generate URLs properly. For example:
.. code-block:: jinja
{% assets filters="cssmin", output="css/style.min.css", "css/inuit.css", "css/pygment-monokai.css", "css/main.css" %}
<link rel="stylesheet" href="{{ SITEURL }}/{{ ASSET_URL }}">
{% endassets %}
... will produce a minified css file with a version identifier that looks like:
.. code-block:: html
<link href="http://{SITEURL}/theme/css/style.min.css?b3a7c807" rel="stylesheet">
These filters can be combined. Here is an example that uses the SASS compiler
and minifies the output:
.. code-block:: jinja
{% assets filters="sass,cssmin", output="css/style.min.css", "css/style.scss" %}
<link rel="stylesheet" href="{{ SITEURL }}/{{ ASSET_URL }}">
{% endassets %}
Another example for Javascript:
.. code-block:: jinja
{% assets filters="uglifyjs", output="js/packed.js", "js/jquery.js", "js/base.js", "js/widgets.js" %}
<script src="{{ SITEURL }}/{{ ASSET_URL }}"></script>
{% endassets %}
The above will produce a minified JS file:
.. code-block:: html
<script src="http://{SITEURL}/theme/js/packed.js?00703b9d"></script>
Pelican's debug mode is propagated to Webassets to disable asset packaging
and instead work with the uncompressed assets.
If you need to create named bundles (for example, if you need to compile SASS
files before minifying with other CSS files), you can use the ``ASSET_BUNDLES``
variable in your settings file. This is an ordered sequence of 3-tuples, where
the 3-tuple is defined as ``(name, args, kwargs)``. This tuple is passed to the
`environment's register() method`_. The following will compile two SCSS files
into a named bundle, using the ``pyscss`` filter:
.. code-block:: python
ASSET_BUNDLES = (
('scss', ['colors.scss', 'main.scss'], {'filters': 'pyscss'}),
)
Many of Webasset's available compilers have additional configuration options
(i.e. 'Less', 'Sass', 'Stylus', 'Closure_js'). You can pass these options to
Webassets using the ``ASSET_CONFIG`` in your settings file.
The following will handle Google Closure's compilation level and locate
LessCSS's binary:
.. code-block:: python
ASSET_CONFIG = (('closure_compressor_optimization', 'WHITESPACE_ONLY'),
('less_bin', 'lessc.cmd'), )
If you wish to place your assets in locations other than the theme output
directory, you can use ``ASSET_SOURCE_PATHS`` in your settings file to provide
webassets with a list of additional directories to search, relative to the
theme's top-level directory:
.. code-block:: python
ASSET_SOURCE_PATHS = [
'vendor/css',
'scss',
]
.. _Webassets: https://github.com/miracle2k/webassets
.. _Webassets documentation: http://webassets.readthedocs.org/en/latest/builtin_filters.html
.. _environment's register() method: http://webassets.readthedocs.org/en/latest/environment.html#registering-bundles
from .assets import *
# -*- coding: utf-8 -*-
"""
Asset management plugin for Pelican
===================================
This plugin allows you to use the `webassets`_ module to manage assets such as
CSS and JS files.
The ASSET_URL is set to a relative url to honor Pelican's RELATIVE_URLS
setting. This requires the use of SITEURL in the templates::
<link rel="stylesheet" href="{{ SITEURL }}/{{ ASSET_URL }}">
.. _webassets: https://webassets.readthedocs.org/
"""
from __future__ import unicode_literals
import os
import logging
from pelican import signals
logger = logging.getLogger(__name__)
try:
import webassets
from webassets import Environment
from webassets.ext.jinja2 import AssetsExtension
except ImportError:
webassets = None
def add_jinja2_ext(pelican):
"""Add Webassets to Jinja2 extensions in Pelican settings."""
if 'JINJA_ENVIRONMENT' in pelican.settings: # pelican 3.7+
pelican.settings['JINJA_ENVIRONMENT']['extensions'].append(AssetsExtension)
else:
pelican.settings['JINJA_EXTENSIONS'].append(AssetsExtension)
def create_assets_env(generator):
"""Define the assets environment and pass it to the generator."""
theme_static_dir = generator.settings['THEME_STATIC_DIR']
assets_destination = os.path.join(generator.output_path, theme_static_dir)
generator.env.assets_environment = Environment(
assets_destination, theme_static_dir)
if 'ASSET_CONFIG' in generator.settings:
for item in generator.settings['ASSET_CONFIG']:
generator.env.assets_environment.config[item[0]] = item[1]
if 'ASSET_BUNDLES' in generator.settings:
for name, args, kwargs in generator.settings['ASSET_BUNDLES']:
generator.env.assets_environment.register(name, *args, **kwargs)
if 'ASSET_DEBUG' in generator.settings:
generator.env.assets_environment.debug = generator.settings['ASSET_DEBUG']
elif logging.getLevelName(logger.getEffectiveLevel()) == "DEBUG":
generator.env.assets_environment.debug = True
for path in (generator.settings['THEME_STATIC_PATHS'] +
generator.settings.get('ASSET_SOURCE_PATHS', [])):
full_path = os.path.join(generator.theme, path)
generator.env.assets_environment.append_path(full_path)
def register():
"""Plugin registration."""
if webassets:
signals.initialized.connect(add_jinja2_ext)
signals.generator_init.connect(create_assets_env)
else:
logger.warning('`assets` failed to load dependency `webassets`.'
'`assets` plugin not loaded.')
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment