document.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. __license__ = '''
  2. This file is part of Dominate.
  3. Dominate is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as
  5. published by the Free Software Foundation, either version 3 of
  6. the License, or (at your option) any later version.
  7. Dominate is distributed in the hope that it will be useful, but
  8. WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General
  12. Public License along with Dominate. If not, see
  13. <http://www.gnu.org/licenses/>.
  14. '''
  15. from . import tags
  16. try:
  17. basestring = basestring
  18. except NameError: # py3
  19. basestring = str
  20. unicode = str
  21. class document(tags.html):
  22. tagname = 'html'
  23. def __init__(self, title='Dominate', doctype='<!DOCTYPE html>', request=None):
  24. '''
  25. Creates a new document instance. Accepts `title`, `doctype`, and `request` keyword arguments.
  26. '''
  27. super(document, self).__init__()
  28. self.doctype = doctype
  29. self.head = super(document, self).add(tags.head())
  30. self.body = super(document, self).add(tags.body())
  31. self.title_node = self.head.add(tags.title(title))
  32. self._entry = self.body
  33. def get_title(self):
  34. return self.title_node.text
  35. def set_title(self, title):
  36. if isinstance(title, basestring):
  37. self.title_node.text = title
  38. else:
  39. self.head.remove(self.title_node)
  40. self.head.add(title)
  41. self.title_node = title
  42. title = property(get_title, set_title)
  43. def add(self, *args):
  44. '''
  45. Adding tags to a document appends them to the <body>.
  46. '''
  47. return self._entry.add(*args)
  48. def render(self, *args, **kwargs):
  49. '''
  50. Creates a <title> tag if not present and renders the DOCTYPE and tag tree.
  51. '''
  52. r = []
  53. #Validates the tag tree and adds the doctype if one was set
  54. if self.doctype:
  55. r.append(self.doctype)
  56. r.append('\n')
  57. r.append(super(document, self).render(*args, **kwargs))
  58. return u''.join(r)
  59. __str__ = __unicode__ = render
  60. def __repr__(self):
  61. return '<dominate.document "%s">' % self.title