diff --git a/liquid_tags/img.py b/liquid_tags/img.py index 22d83e436..d38163a3a 100644 --- a/liquid_tags/img.py +++ b/liquid_tags/img.py @@ -22,6 +22,7 @@ [1] https://github.com/imathis/octopress/blob/master/plugins/image_tag.rb """ +import os import re from .mdx_liquid_tags import LiquidTags import six @@ -29,11 +30,13 @@ SYNTAX = '{% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | "title text" ["alt text"]] %}' # Regular expression to match the entire syntax -ReImg = re.compile("""(?P\S.*\s+)?(?P(?:https?:\/\/|\/|\S+\/)\S+)(?:\s+(?P\d+))?(?:\s+(?P\d+))?(?P\s+.+)?""") +ReImg = re.compile(r'(?P<class>[-\w\s]+\s+)?(?P<src>(?P<scheme>[a-zA-Z]+://)?(?P<path>\S+))(?:\s+(?P<width>\d+))?(?:\s+(?P<height>\d+))?(?P<title>\s+.+)?') # Regular expression to split the title and alt text ReTitleAlt = re.compile("""(?:"|')(?P<title>[^"']+)?(?:"|')\s+(?:"|')(?P<alt>[^"']+)?(?:"|')""") +# Attributes to keep in the emmitted img tag +IMG_ATTRS = ['class', 'src', 'width', 'height', 'title',] @LiquidTags.register('img') def img(preprocessor, tag, markup): @@ -42,8 +45,7 @@ def img(preprocessor, tag, markup): # Parse the markup string match = ReImg.search(markup) if match: - attrs = dict([(key, val.strip()) - for (key, val) in six.iteritems(match.groupdict()) if val]) + attrs = {k: v.strip() for k, v in match.groupdict().items() if v} else: raise ValueError('Error processing input. ' 'Expected syntax: {0}'.format(SYNTAX)) @@ -56,9 +58,17 @@ def img(preprocessor, tag, markup): if not attrs.get('alt'): attrs['alt'] = attrs['title'] - # Return the formatted text - return "<img {0}>".format(' '.join('{0}="{1}"'.format(key, val) - for (key, val) in six.iteritems(attrs))) + # prepend site url to absolute paths + if 'scheme' not in attrs and os.path.isabs(attrs['src']): + siteurl = preprocessor.configs.getConfig('SITEURL') + attrs['src'] = siteurl + attrs['path'] + + # create tag + img_attrs = ['{0!s}={1!r}'.format(k, attrs[k]) + for k in IMG_ATTRS if attrs.get(k)] + s = "<img {0}>".format(' '.join(img_attrs)) + logging.error(s) + return s #---------------------------------------------------------------------- # This import allows image tag to be a Pelican plugin diff --git a/liquid_tags/mdx_liquid_tags.py b/liquid_tags/mdx_liquid_tags.py index ca20514a4..a7e97e97e 100644 --- a/liquid_tags/mdx_liquid_tags.py +++ b/liquid_tags/mdx_liquid_tags.py @@ -21,12 +21,15 @@ 'FLICKR_API_KEY': 'flickr', 'GIPHY_API_KEY': 'giphy', 'LT_DELIMITERS': ('{%', '%}'), + 'SITEURL': '', } LT_HELP = { 'CODE_DIR' : 'Code directory for include_code subplugin', 'NOTEBOOK_DIR' : 'Notebook directory for notebook subplugin', 'FLICKR_API_KEY': 'Flickr key for accessing the API', 'GIPHY_API_KEY': 'Giphy key for accessing the API', 'LT_DELIMITERS': 'Alternative set of Liquid Tags block delimiters', + 'SITEURL': 'Base URL of your web site. ' + 'Inserted before absolute media paths.', } class _LiquidTagsPreprocessor(markdown.preprocessors.Preprocessor):