img.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. import six
  24. SYNTAX = '{% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | "title text" ["alt text"]] %}'
  25. # Regular expression to match the entire syntax
  26. ReImg = re.compile("""(?P<class>\S.*\s+)?(?P<src>(?:https?:\/\/|\/|\S+\/)\S+)(?:\s+(?P<width>\d+))?(?:\s+(?P<height>\d+))?(?P<title>\s+.+)?""")
  27. # Regular expression to split the title and alt text
  28. ReTitleAlt = re.compile("""(?:"|')(?P<title>[^"']+)?(?:"|')\s+(?:"|')(?P<alt>[^"']+)?(?:"|')""")
  29. @LiquidTags.register('img')
  30. def img(preprocessor, tag, markup):
  31. attrs = None
  32. # Parse the markup string
  33. match = ReImg.search(markup)
  34. if match:
  35. attrs = dict([(key, val.strip())
  36. for (key, val) in six.iteritems(match.groupdict()) if val])
  37. else:
  38. raise ValueError('Error processing input. '
  39. 'Expected syntax: {0}'.format(SYNTAX))
  40. # Check if alt text is present -- if so, split it from title
  41. if 'title' in attrs:
  42. match = ReTitleAlt.search(attrs['title'])
  43. if match:
  44. attrs.update(match.groupdict())
  45. if not attrs.get('alt'):
  46. attrs['alt'] = attrs['title']
  47. # Return the formatted text
  48. return "<img {0}>".format(' '.join('{0}="{1}"'.format(key, val)
  49. for (key, val) in six.iteritems(attrs)))
  50. #----------------------------------------------------------------------
  51. # This import allows image tag to be a Pelican plugin
  52. from .liquid_tags import register