Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2Shortcuts, especially for working with Django templates in an ad-hoc manner. 

3 

4""" 

5 

6# Imports 

7 

8from django.template import Context, loader, Template 

9from django.template.exceptions import TemplateDoesNotExist 

10 

11# Exports 

12 

13__all__ = ( 

14 "parse_string", 

15 "parse_template", 

16 "template_exists", 

17) 

18 

19# Functions 

20 

21 

22def parse_string(string, context): 

23 """Parse a string as a Django template. 

24 

25 :param string: The name of the template. 

26 :type string: str 

27 

28 :param context: Context variables. 

29 :type context: dict 

30 

31 :rtype: str 

32 

33 """ 

34 template = Template(string) 

35 return template.render(Context(context)) 

36 

37 

38def parse_template(template, context): 

39 """Ad hoc means of parsing a template using Django's built-in loader. 

40 

41 :param template: The name of the template. 

42 :type template: str || unicode 

43 

44 :param context: Context variables. 

45 :type context: dict 

46 

47 :rtype: str 

48 

49 """ 

50 return loader.render_to_string(template, context) 

51 

52 

53def template_exists(name): 

54 """Indicates whether the given template exists. 

55 

56 :param name: The name (path) of the template to load. 

57 :type name: str 

58 

59 :rtype: bool 

60 

61 """ 

62 try: 

63 loader.get_template(name) 

64 return True 

65 except TemplateDoesNotExist: 

66 return False