Skip to content

Commit

Permalink
add_stylesheet() allows additional attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
tk0miya committed Apr 6, 2018
1 parent 6030e73 commit c5d6942
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 16 deletions.
1 change: 1 addition & 0 deletions CHANGES
Expand Up @@ -58,6 +58,7 @@ Features added
* LaTeX: new key ``'fvset'`` for :confval:`latex_elements`. For
XeLaTeX/LuaLaTeX its default sets ``fanvyvrb`` to use normal, not small,
fontsize in code-blocks (refs: #4793)
* ``app.add_stylesheet()`` allows additional attributes

Bugs fixed
----------
Expand Down
36 changes: 27 additions & 9 deletions sphinx/application.py
Expand Up @@ -1001,13 +1001,27 @@ def add_javascript(self, filename):
StandaloneHTMLBuilder.script_files.append(
posixpath.join('_static', filename))

def add_stylesheet(self, filename, alternate=False, title=None):
# type: (unicode, bool, unicode) -> None
def add_stylesheet(self, filename, **kwargs):
# type: (unicode, **unicode) -> None
"""Register a stylesheet to include in the HTML output.
Add *filename* to the list of CSS files that the default HTML template
will include. Like for :meth:`add_javascript`, the filename must be
relative to the HTML static path, or a full URI with scheme.
will include. The filename must be relative to the HTML static path,
or a full URI with scheme. The keyword arguments are also accepted for
attributes of ``<link>`` tag.
Example::
app.add_stylesheet('custom.css')
# => <link rel="stylesheet" href="_static/custom.css" type="text/css" />
app.add_stylesheet('print.css', media='print')
# => <link rel="stylesheet" href="_static/print.css"
# type="text/css" media="print" />
app.add_stylesheet('fancy.css', rel='alternate stylesheet', title='fancy')
# => <link rel="alternate stylesheet" href="_static/fancy.css"
# type="text/css" title="fancy" />
.. versionadded:: 1.0
Expand All @@ -1017,16 +1031,20 @@ def add_stylesheet(self, filename, alternate=False, title=None):
arguments. The default is no title and *alternate* = ``False``. For
more information, refer to the `documentation
<https://mdn.io/Web/CSS/Alternative_style_sheets>`__.
.. versionchanged:: 1.8
Allows keyword arguments as attributes of link tag.
"""
logger.debug('[app] adding stylesheet: %r', filename)
from sphinx.builders.html import StandaloneHTMLBuilder, Stylesheet
if '://' not in filename:
filename = posixpath.join('_static', filename)
if alternate:
rel = u'alternate stylesheet'
else:
rel = u'stylesheet'
css = Stylesheet(filename, title, rel) # type: ignore
if kwargs.pop('alternate', None):
warnings.warn('The alternate option for app.add_stylesheet() is deprecated. '
'Please use rel="alternate stylesheet" option instead.',
RemovedInSphinx30Warning)
kwargs['rel'] = 'alternate stylesheet'
css = Stylesheet(filename, **kwargs)
StandaloneHTMLBuilder.css_files.append(css)

def add_latex_package(self, packagename, options=None):
Expand Down
26 changes: 21 additions & 5 deletions sphinx/builders/html.py
Expand Up @@ -50,6 +50,7 @@
from sphinx.util.nodes import inline_all_toctrees
from sphinx.util.osutil import SEP, os_path, relative_uri, ensuredir, \
movefile, copyfile
from sphinx.util.pycompat import htmlescape
from sphinx.writers.html import HTMLWriter, HTMLTranslator

if False:
Expand Down Expand Up @@ -101,7 +102,7 @@ def append(self, obj):
if isinstance(obj, Stylesheet):
super(CSSContainer, self).append(obj)
else:
super(CSSContainer, self).append(Stylesheet(obj, None, 'stylesheet')) # type: ignore # NOQA
super(CSSContainer, self).append(Stylesheet(obj))

def insert(self, index, obj):
# type: (int, Union[unicode, Stylesheet]) -> None
Expand All @@ -111,7 +112,7 @@ def insert(self, index, obj):
if isinstance(obj, Stylesheet):
super(CSSContainer, self).insert(index, obj)
else:
super(CSSContainer, self).insert(index, Stylesheet(obj, None, 'stylesheet')) # type: ignore # NOQA
super(CSSContainer, self).insert(index, Stylesheet(obj))

def extend(self, other): # type: ignore
# type: (List[Union[unicode, Stylesheet]]) -> None
Expand Down Expand Up @@ -144,12 +145,18 @@ class Stylesheet(text_type):
its filename (str).
"""

def __new__(cls, filename, title, rel):
attributes = None # type: Dict[unicode, unicode]
filename = None # type: unicode

def __new__(cls, filename, *args, **attributes):
# type: (unicode, unicode, unicode) -> None
self = text_type.__new__(cls, filename) # type: ignore
self.filename = filename
self.title = title
self.rel = rel
self.attributes = attributes
self.attributes.setdefault('rel', 'stylesheet')
if args: # old style arguments (rel, title)
self.attributes['rel'] = args[0]
self.attributes['title'] = args[1]

return self

Expand Down Expand Up @@ -988,6 +995,15 @@ def pathto(otheruri, resource=False, baseuri=default_baseuri):
return uri
ctx['pathto'] = pathto

def css_tag(css):
# type: (Stylesheet) -> unicode
attrs = ['%s="%s"' % (key, htmlescape(value, True))
for key, value in css.attributes.items()
if value is not None]
attrs.append('href="%s"' % pathto(css.filename, resource=True))
return '<link %s />' % ' '.join(attrs)
ctx['css_tag'] = css_tag

def hasdoc(name):
# type: (unicode) -> bool
if name in self.env.all_docs:
Expand Down
4 changes: 2 additions & 2 deletions sphinx/themes/basic/layout.html
Expand Up @@ -97,8 +97,8 @@ <h3>{{ _('Navigation') }}</h3>
<link rel="stylesheet" href="{{ pathto('_static/' + style, 1) }}" type="text/css" />
<link rel="stylesheet" href="{{ pathto('_static/pygments.css', 1) }}" type="text/css" />
{%- for css in css_files %}
{%- if css|attr("rel") %}
<link rel="{{ css.rel }}" href="{{ pathto(css.filename, 1) }}" type="text/css"{% if css.title is not none %} title="{{ css.title }}"{% endif %} />
{%- if css|attr("filename") %}
{{ css_tag(css) }}
{%- else %}
<link rel="stylesheet" href="{{ pathto(css, 1) }}" type="text/css" />
{%- endif %}
Expand Down

0 comments on commit c5d6942

Please sign in to comment.