The blog.
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

80 rindas
1.9 KiB

  1. from jinja2 import contextfilter, environmentfilter
  2. from jinja2.ext import Extension
  3. from io import StringIO
  4. from lxml import etree
  5. @contextfilter
  6. def rellinktoabs(context, value):
  7. env = context.environment
  8. # get the path for this context
  9. rel_path = context['resource'].relative_path
  10. content_url = env.globals['content_url'](context, rel_path)
  11. html = etree.HTML(value)
  12. # get all the fragment urls
  13. r = html.xpath("//a[@href[starts-with(.,'#')]]")
  14. for i in r:
  15. # prefix them w/ the content_url
  16. i.attrib['href'] = content_url + i.attrib['href']
  17. res = etree.tostring(html, encoding='unicode', method='html')
  18. # lxml.HTML wraps the html w/ html/body tags, strip them
  19. # if present
  20. startstr = '<html><body>'
  21. endstr = '</body></html>'
  22. startpos = 0
  23. endpos = None
  24. if res.startswith(startstr):
  25. startpos = len(startstr)
  26. if res.endswith(endstr):
  27. endpos = -len(endstr)
  28. res = res[startpos:endpos]
  29. return res
  30. # mostly copied from hyde.ext.templates.jinja.py Markdown
  31. # and using docs from:
  32. # https://jinja.palletsprojects.com/en/2.10.x/extensions/#example-extension
  33. # to get the filter installed
  34. class RelLinktoAbs(Extension):
  35. """
  36. A wrapper around the rellinktoabs filter for syntactic sugar.
  37. """
  38. tags = { 'rellinktoabs' }
  39. def __init__(self, env):
  40. super(RelLinktoAbs, self).__init__(env)
  41. env.filters['rellinktoabs'] = rellinktoabs
  42. def parse(self, parser):
  43. """
  44. Parses the statements and defers to the callback
  45. for rellinktoabs processing.
  46. """
  47. lineno = next(parser.stream).lineno
  48. body = parser.parse_statements(['name:endrellinktoabs'], drop_needle=True)
  49. return nodes.CallBlock(
  50. self.call_method('_render_rellinktoabs'),
  51. [], [], body).set_lineno(lineno)
  52. def _render_rellinktoabs(self, caller=None):
  53. """
  54. Calls the rellinktoabs filter to transform the output.
  55. """
  56. if not caller:
  57. return ''
  58. output = caller().strip()
  59. return rellinktoabs(self.environment, output)