img.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. Image Tag
  3. ---------
  4. This implements a Liquid-style image tag for Pelican,
  5. based on the octopress image tag [1]_
  6. Syntax
  7. ------
  8. {% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | "title text" ["alt text"]] %}
  9. Examples
  10. --------
  11. {% img /images/ninja.png Ninja Attack! %}
  12. {% img left half http://site.com/images/ninja.png Ninja Attack! %}
  13. {% img left half http://site.com/images/ninja.png 150 150 "Ninja Attack!" "Ninja in attack posture" %}
  14. Output
  15. ------
  16. <img src="/images/ninja.png">
  17. <img class="left half" src="http://site.com/images/ninja.png" title="Ninja Attack!" alt="Ninja Attack!">
  18. <img class="left half" src="http://site.com/images/ninja.png" width="150" height="150" title="Ninja Attack!" alt="Ninja in attack posture">
  19. [1] https://github.com/imathis/octopress/blob/master/plugins/image_tag.rb
  20. """
  21. import re
  22. from .mdx_liquid_tags import LiquidTags
  23. SYNTAX = '{% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | "title text" ["alt text"]] %}'
  24. # Regular expression to match the entire syntax
  25. ReImg = re.compile("""(?P<class>\S.*\s+)?(?P<src>(?:https?:\/\/|\/|\S+\/)\S+)(?:\s+(?P<width>\d+))?(?:\s+(?P<height>\d+))?(?P<title>\s+.+)?""")
  26. # Regular expression to split the title and alt text
  27. ReTitleAlt = re.compile("""(?:"|')(?P<title>[^"']+)?(?:"|')\s+(?:"|')(?P<alt>[^"']+)?(?:"|')""")
  28. @LiquidTags.register('img')
  29. def img(preprocessor, tag, markup):
  30. attrs = None
  31. # Parse the markup string
  32. match = ReImg.search(markup)
  33. if match:
  34. attrs = dict([(key, val.strip())
  35. for (key, val) in match.groupdict().iteritems() if val])
  36. else:
  37. raise ValueError('Error processing input. '
  38. 'Expected syntax: {0}'.format(SYNTAX))
  39. # Check if alt text is present -- if so, split it from title
  40. if 'title' in attrs:
  41. match = ReTitleAlt.search(attrs['title'])
  42. if match:
  43. attrs.update(match.groupdict())
  44. if not attrs.get('alt'):
  45. attrs['alt'] = attrs['title']
  46. # Return the formatted text
  47. return "<img {0}>".format(' '.join('{0}="{1}"'.format(key, val)
  48. for (key, val) in attrs.iteritems()))
  49. #----------------------------------------------------------------------
  50. # This import allows image tag to be a Pelican plugin
  51. from liquid_tags import register