Knio / dominate

Dominate is a Python library for creating and manipulating HTML documents using an elegant DOM API. It allows you to write HTML pages in pure Python very concisely, which eliminate the need to learn another template language, and to take advantage of the more powerful features of Python.
GNU Lesser General Public License v3.0
1.71k stars 110 forks source link

cannot put <meta charset=""> first #140

Open allefeld opened 3 years ago

allefeld commented 3 years ago

In HTML5 it is recommended to explicitly specify the character encoding with a meta element in the head:

<meta charset="utf-8">

To make sure this encoding is also applied to the title of the document, it should come before the title element. However, if I try to do so with the code

import dominate
doc = dominate.document()
with doc.head:
    dominate.tags.meta(charset='utf-8')
    dominate.tags.title('Document title')
print(doc.render())

the result is

<!DOCTYPE html>
<html>
  <head>
    <title>Dominate</title>
    <meta charset="utf-8">
    <title>Document title</title>
  </head>
  <body></body>
</html>

i.e. I get two title elements. If I specify the title instead as an argument of dominate.document, there is only one title element, but it is before the meta element.

I see two ways around this:

1) The title attribute of dominate.document is only used to generate a title element if none has been added manually.

2) dominate.document gets an additional charset argument.

My preference would be (1).

Knio commented 3 years ago

document is a thin wrapper that's pretty much just for quick prototyping. If you want more control, I would suggest just using tags.html as your root element instead of document. Other simple things you could do is just removing doc.title_node or doing doc.children.insert(0, meta_node).

If this is more of a feature request than a bug report, adding an automatic meta tag to document (in the right place) could be a good idea.

allefeld commented 3 years ago

Honestly not sure whether this is a bug report or a feature request. ;) But I agree, document could be more than just for prototyping, but a convenience function which makes sure that things like <meta charset=""> are there.

I wasn't aware that I could use tags.html instead of document, thanks! But then, how do I get the <!DOCTYPE html>? Just write it myself?

ipapop commented 3 years ago

I have a similar issue trying to set the doc rendered opening html tag to html lang="en" using dominate.tags.html I guess it is rather a feature request though.. Edit : as a workaround I am using beautiful soup to modify the opening html tag..