Skip to content

Commit

Permalink
liquid_tags: Prepend SITEURL to src when it is an absolute path.
Browse files Browse the repository at this point in the history
This is useful when the live site is hosted in a subdirectory
(e.g. http://www.foo.bar/mysite) to avoid having to repeat /mysite
every time.
  • Loading branch information
m000 committed Jun 13, 2020
1 parent d8ab315 commit c4395b6
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions liquid_tags/img.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,21 @@
[1] https://github.com/imathis/octopress/blob/master/plugins/image_tag.rb
"""
import os
import re
from .mdx_liquid_tags import LiquidTags
import six

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<class>\S.*\s+)?(?P<src>(?:https?:\/\/|\/|\S+\/)\S+)(?:\s+(?P<width>\d+))?(?:\s+(?P<height>\d+))?(?P<title>\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):
Expand All @@ -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))
Expand All @@ -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
Expand Down

0 comments on commit c4395b6

Please sign in to comment.