Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Merge pull request #1960 from getnikola/fix-1939
Rewrite srcset links,  Fix #1939
  • Loading branch information
da2x committed Aug 21, 2015
2 parents 8d87914 + 8e00835 commit 2b9b86a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGES.txt
Expand Up @@ -12,6 +12,7 @@ Features
Bugfixes
--------

* Rewrite srcset links (Issue #1939)
* Add dependencies for include tag in Mako (Issue #1956)
* Don’t duplicate BLOG_TITLE in the front page title (Issue #1952)
* Escape instad of strip HTML in titles (Issue #1952)
Expand Down
15 changes: 14 additions & 1 deletion nikola/nikola.py
Expand Up @@ -1053,11 +1053,24 @@ def render_template(self, template_name, output_name, context):
utils.makedirs(os.path.dirname(output_name))
parser = lxml.html.HTMLParser(remove_blank_text=True)
doc = lxml.html.document_fromstring(data, parser)
doc.rewrite_links(lambda dst: self.url_replacer(src, dst, context['lang']), resolve_base_href=False)
self.rewrite_links(doc, src, context['lang'])
data = b'<!DOCTYPE html>\n' + lxml.html.tostring(doc, encoding='utf8', method='html', pretty_print=True)
with open(output_name, "wb+") as post_file:
post_file.write(data)

def rewrite_links(self, doc, src, lang):
"""Replace links in document to point to the right places."""
# First let lxml replace most of them
doc.rewrite_links(lambda dst: self.url_replacer(src, dst, lang), resolve_base_href=False)

# lxml ignores srcset in img and source elements, so do that by hand
objs = list(doc.findall('*//img')) + list(doc.findall('*//source'))
for obj in objs:
if 'srcset' in obj.attrib:
urls = [u.strip() for u in obj.attrib['srcset'].split(',')]
urls = [self.url_replacer(src, dst, lang) for dst in urls]
obj.set('srcset', ', '.join(urls))

def url_replacer(self, src, dst, lang=None, url_type=None):
"""Mangle URLs.
Expand Down

0 comments on commit 2b9b86a

Please sign in to comment.