Coverage for /Users/davegaeddert/Development/dropseed/plain/plain/plain/views/templates.py: 88%

1 from plain.csrf.middleware import get_token

2 from plain.exceptions import ImproperlyConfigured

3 from plain.runtime import settings

4 from plain.templates import Template, TemplateFileMissing

5 from plain.utils.functional import lazy

6 from plain.utils.html import format_html

7 from plain.utils.safestring import SafeString

8

9 from .base import View

10

11

12 def csrf_input(request):

13 return format_html(

14 '<input type="hidden" name="csrfmiddlewaretoken" value="{}">',

15 get_token(request),

16 )

17

18

19 csrf_input_lazy = lazy(csrf_input, SafeString, str)

20 csrf_token_lazy = lazy(get_token, str)

21

22

23 class TemplateView(View):

24 """

25 Render a template. Pass keyword arguments from the URLconf to the context.

26 """

27

28 template_name: str | None = None

29

30 def get_template_context(self) -> dict:

31 return {

32 "request": self.request,

33 "csrf_input": csrf_input_lazy(self.request),

34 "csrf_token": csrf_token_lazy(self.request),

35 "DEBUG": settings.DEBUG,

36 }

37

38 def get_template_names(self) -> list[str]:

39 """

40 Return a list of template names to be used for the request. Must return

41 a list. May not be called if render_to_response() is overridden.

42 """

43 if self.template_name is None:

44 raise ImproperlyConfigured(

45 "TemplateView requires either a definition of "

46 "'template_name' or an implementation of 'get_template_names()'"

47 )

48 else:

49 return [self.template_name]

50

51 def get_template(self) -> Template:

52 template_names = self.get_template_names()

53

54 for template_name in template_names:

55 try:

56 return Template(template_name)

57 except TemplateFileMissing:

58 pass

59

60 raise TemplateFileMissing(template_names)

61

62 def render_template(self) -> str:

63 return self.get_template().render(self.get_template_context())

64

65 def get(self):

66 return self.render_template()