summaryrefslogtreecommitdiff
path: root/plugins/pelican-css-js/pelican_css_js.py
blob: 1b07e6850509a67d467040eddb710f44e4265e29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""
Include JavaScript and CSS files for Pelican
============================================

This plugin allows you to easily embed JS and CSS in the header of individual
articles.
"""
import os
import shutil

from pelican import signals


def copy_resources(src, dest, file_list):
    """
    Copy files from content folder to output folder

    Parameters
    ----------
    src: string
        Content folder path
    dest: string,
        Output folder path
    file_list: list
        List of files to be transferred

    Output
    ------
    Copies files from content to output
    """
    if not os.path.exists(dest):
        os.makedirs(dest)
    for file_ in file_list:
        file_src = os.path.join(src, file_)
        shutil.copy2(file_src, dest)


def add_files(gen, metadata):
    """
    The registered handler for the dynamic resources plugin. It will
    add the javascripts and/or stylesheets to the article
    """
    site_url = gen.settings['SITEURL']
    formatters = {
        'styles': '<link rel="stylesheet" href="{0}" type="text/css" />',
        'js': '<script src="{0}"></script>'
    }
    dirnames = {'styles': 'css',
                'js': 'js'}
    for key in ['styles', 'js']:
        if key in metadata:
            files = metadata[key].replace(" ", "").split(",")
            htmls = []
            for f in files:
                if f.startswith('http://') or f.startswith('https://'):
                    link = f
                else:
                    if gen.settings['RELATIVE_URLS']:
                        link = "%s/%s/%s" % ('..', dirnames[key], f)
                    else:
                        link = "%s/%s/%s" % (site_url, dirnames[key], f)
                html = formatters[key].format(link)
                htmls.append(html)
            metadata[key] = htmls


def move_resources(gen):
    """
    Move files from js/css folders to output folder
    """
    js_files = gen.get_files('js', extensions='js')
    css_files = gen.get_files('css', extensions='css')

    js_dest = os.path.join(gen.output_path, 'js')
    copy_resources(gen.path, js_dest, js_files)

    css_dest = os.path.join(gen.output_path, 'css')
    copy_resources(gen.path, css_dest, css_files)


def register():
    """
    Plugin registration
    """
    signals.article_generator_context.connect(add_files)
    signals.page_generator_context.connect(add_files)
    signals.article_generator_finalized.connect(move_resources)