read_more_link.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. """
  3. Read More Link
  4. ===========================
  5. This plugin inserts an inline "read more" or "continue" link into the last html element of the object summary.
  6. For more information, please visit: http://vuongnguyen.com/creating-inline-read-more-link-python-pelican-lxml.html
  7. """
  8. from pelican import signals, contents
  9. from pelican.utils import truncate_html_words
  10. try:
  11. from lxml.html import fragment_fromstring, fragments_fromstring, tostring
  12. from lxml.etree import ParserError
  13. except ImportError:
  14. raise Exception("Unable to find lxml. To use READ_MORE_LINK, you need lxml")
  15. def insert_into_last_element(html, element):
  16. """
  17. function to insert an html element into another html fragment
  18. example:
  19. html = '<p>paragraph1</p><p>paragraph2...</p>'
  20. element = '<a href="/read-more/">read more</a>'
  21. ---> '<p>paragraph1</p><p>paragraph2...<a href="/read-more/">read more</a></p>'
  22. """
  23. try:
  24. item = fragment_fromstring(element)
  25. except (ParserError, TypeError) as e:
  26. item = fragment_fromstring('<span></span>')
  27. try:
  28. doc = fragments_fromstring(html)
  29. doc[-1].append(item)
  30. return ''.join(tostring(e) for e in doc)
  31. except (ParserError, TypeError) as e:
  32. return ''
  33. def insert_read_more_link(instance):
  34. """
  35. Insert an inline "read more" link into the last element of the summary
  36. :param instance:
  37. :return:
  38. """
  39. # only deals with Article type
  40. if type(instance) != contents.Article: return
  41. SUMMARY_MAX_LENGTH = instance.settings.get('SUMMARY_MAX_LENGTH')
  42. READ_MORE_LINK = instance.settings.get('READ_MORE_LINK', None)
  43. READ_MORE_LINK_FORMAT = instance.settings.get('READ_MORE_LINK_FORMAT',
  44. '<a class="read-more" href="/{url}">{text}</a>')
  45. if not (SUMMARY_MAX_LENGTH and READ_MORE_LINK and READ_MORE_LINK_FORMAT): return
  46. if hasattr(instance, '_summary') and instance._summary:
  47. summary = instance._summary
  48. else:
  49. summary = truncate_html_words(instance.content, SUMMARY_MAX_LENGTH)
  50. if summary<instance.content:
  51. read_more_link = READ_MORE_LINK_FORMAT.format(url=instance.url, text=READ_MORE_LINK)
  52. instance._summary = insert_into_last_element(summary, read_more_link)
  53. def register():
  54. signals.content_object_init.connect(insert_read_more_link)