add support for relative cross-site links

This commit is contained in:
Bruno Binet 2012-12-01 18:22:43 +01:00
commit a0504aeabe
7 changed files with 26 additions and 19 deletions

View file

@ -134,7 +134,8 @@ class Pelican(object):
"""Run the generators and return""" """Run the generators and return"""
context = self.settings.copy() context = self.settings.copy()
filenames = {} # share the dict between all the generators context['filenames'] = {} # share the dict between all the generators
context['localsiteurl'] = self.settings.get('SITEURL') # share
generators = [ generators = [
cls( cls(
context, context,
@ -143,8 +144,6 @@ class Pelican(object):
self.theme, self.theme,
self.output_path, self.output_path,
self.markup, self.markup,
self.delete_outputdir,
filenames=filenames
) for cls in self.get_generator_classes() ) for cls in self.get_generator_classes()
] ]

View file

@ -5,7 +5,6 @@ import logging
import functools import functools
import os import os
import re import re
import urlparse
from datetime import datetime from datetime import datetime
from sys import platform, stdin from sys import platform, stdin
@ -132,11 +131,13 @@ class Page(object):
key = key if self.in_default_lang else 'lang_%s' % key key = key if self.in_default_lang else 'lang_%s' % key
return self._expand_settings(key) return self._expand_settings(key)
def _update_content(self, content): def _update_content(self, content, siteurl):
"""Change all the relative paths of the content to relative paths """Change all the relative paths of the content to relative paths
suitable for the ouput content. suitable for the ouput content.
:param content: content resource that will be passed to the templates. :param content: content resource that will be passed to the templates.
:param siteurl: siteurl which is locally generated by the writer in
case of RELATIVE_URLS.
""" """
hrefs = re.compile(r""" hrefs = re.compile(r"""
(?P<markup><\s*[^\>]* # match tag with src and href attr (?P<markup><\s*[^\>]* # match tag with src and href attr
@ -163,8 +164,8 @@ class Page(object):
) )
if value in self._context['filenames']: if value in self._context['filenames']:
origin = urlparse.urljoin(self._context['SITEURL'], origin = '/'.join((siteurl,
self._context['filenames'][value].url) self._context['filenames'][value].url))
else: else:
logger.warning(u"Unable to find {fn}, skipping url" logger.warning(u"Unable to find {fn}, skipping url"
" replacement".format(fn=value)) " replacement".format(fn=value))
@ -174,15 +175,16 @@ class Page(object):
return hrefs.sub(replacer, content) return hrefs.sub(replacer, content)
@property
@memoized @memoized
def get_content(self, siteurl):
return self._update_content(
self._get_content() if hasattr(self, "_get_content")
else self._content,
siteurl)
@property
def content(self): def content(self):
if hasattr(self, "_get_content"): return self.get_content(self._context['localsiteurl'])
content = self._get_content()
else:
content = self._content
content = self._update_content(content)
return content
def _get_summary(self): def _get_summary(self):
"""Returns the summary of an article, based on the summary metadata """Returns the summary of an article, based on the summary metadata

View file

@ -63,7 +63,6 @@ class Generator(object):
# get custom Jinja filters from user settings # get custom Jinja filters from user settings
custom_filters = self.settings.get('JINJA_FILTERS', {}) custom_filters = self.settings.get('JINJA_FILTERS', {})
self.env.filters.update(custom_filters) self.env.filters.update(custom_filters)
self.context['filenames'] = kwargs.get('filenames', {})
signals.generator_init.send(self) signals.generator_init.send(self)

View file

@ -39,7 +39,7 @@ class Writer(object):
link='%s/%s' % (self.site_url, item.url), link='%s/%s' % (self.site_url, item.url),
unique_id='tag:%s,%s:%s' % (self.site_url.replace('http://', ''), unique_id='tag:%s,%s:%s' % (self.site_url.replace('http://', ''),
item.date.date(), item.url), item.date.date(), item.url),
description=item.content, description=item.get_content(self.site_url),
categories=item.tags if hasattr(item, 'tags') else None, categories=item.tags if hasattr(item, 'tags') else None,
author_name=getattr(item, 'author', ''), author_name=getattr(item, 'author', ''),
pubdate=set_date_tzinfo(item.date, pubdate=set_date_tzinfo(item.date,
@ -124,7 +124,9 @@ class Writer(object):
localcontext = context.copy() localcontext = context.copy()
if relative_urls: if relative_urls:
localcontext['SITEURL'] = get_relative_path(name) relative_path = get_relative_path(name)
context['localsiteurl'] = relative_path
localcontext['SITEURL'] = relative_path
localcontext.update(kwargs) localcontext.update(kwargs)

View file

@ -19,6 +19,9 @@ class TestPage(unittest.TestCase):
super(TestPage, self).setUp() super(TestPage, self).setUp()
self.page_kwargs = { self.page_kwargs = {
'content': TEST_CONTENT, 'content': TEST_CONTENT,
'context': {
'localsiteurl': '',
},
'metadata': { 'metadata': {
'summary': TEST_SUMMARY, 'summary': TEST_SUMMARY,
'title': 'foo bar', 'title': 'foo bar',
@ -32,7 +35,8 @@ class TestPage(unittest.TestCase):
""" """
metadata = {'foo': 'bar', 'foobar': 'baz', 'title': 'foobar', } metadata = {'foo': 'bar', 'foobar': 'baz', 'title': 'foobar', }
page = Page(TEST_CONTENT, metadata=metadata) page = Page(TEST_CONTENT, metadata=metadata,
context={'localsiteurl': ''})
for key, value in metadata.items(): for key, value in metadata.items():
self.assertTrue(hasattr(page, key)) self.assertTrue(hasattr(page, key))
self.assertEqual(value, getattr(page, key)) self.assertEqual(value, getattr(page, key))

View file

@ -96,6 +96,7 @@ class TestArticlesGenerator(unittest.TestCase):
settings['DEFAULT_CATEGORY'] = 'Default' settings['DEFAULT_CATEGORY'] = 'Default'
settings['DEFAULT_DATE'] = (1970, 01, 01) settings['DEFAULT_DATE'] = (1970, 01, 01)
settings['USE_FOLDER_AS_CATEGORY'] = False settings['USE_FOLDER_AS_CATEGORY'] = False
settings['filenames'] = {}
generator = ArticlesGenerator(settings.copy(), settings, generator = ArticlesGenerator(settings.copy(), settings,
CUR_DIR, _DEFAULT_CONFIG['THEME'], None, CUR_DIR, _DEFAULT_CONFIG['THEME'], None,
_DEFAULT_CONFIG['MARKUP']) _DEFAULT_CONFIG['MARKUP'])

View file

@ -81,7 +81,7 @@ class TestPelican(unittest.TestCase):
self.assertEqual(self.logcount_handler.count_logs( self.assertEqual(self.logcount_handler.count_logs(
msg="Unable to find.*skipping url replacement", msg="Unable to find.*skipping url replacement",
level=logging.WARNING, level=logging.WARNING,
), 4, msg="bad number of occurences found for this log") ), 10, msg="bad number of occurences found for this log")
def test_custom_generation_works(self): def test_custom_generation_works(self):
# the same thing with a specified set of settings should work # the same thing with a specified set of settings should work