Coverage for app/venv/lib/python3.14/site-packages/weblate/accounts/templatetags/site_url.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 07:15 +0000

1# Copyright © Michal Čihař <michal@weblate.org> 

2# 

3# SPDX-License-Identifier: GPL-3.0-or-later 

4 

5"""Convert any links in HTML to absolute.""" 

6 

7from io import StringIO 

8 

9from django import template 

10from django.utils.safestring import mark_safe 

11from lxml import etree 

12 

13from weblate.utils.site import get_site_url 

14 

15register = template.Library() 

16 

17 

18@register.filter 

19def add_site_url(content): 

20 """Automatically add site URL to any relative links or images.""" 

21 parser = etree.HTMLParser(collect_ids=False) 

22 tree = etree.parse(StringIO(content), parser) 

23 for link in tree.findall(".//a"): 

24 url = link.get("href") 

25 if url.startswith("/"): 

26 link.set("href", get_site_url(url)) 

27 for link in tree.findall(".//img"): 

28 url = link.get("src") 

29 if url.startswith("/"): 

30 link.set("src", get_site_url(url)) 

31 

32 body = tree.find("body") 

33 return mark_safe( # noqa: S308 

34 "".join( 

35 [ 

36 etree.tostring( 

37 child, pretty_print=True, method="html", encoding="unicode" 

38 ) 

39 for child in body.iterchildren() 

40 ] 

41 ) 

42 )