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.72k stars 108 forks source link

Unable to create custom tags containing hyphens instead of underscores #120

Closed jakogut closed 4 years ago

jakogut commented 4 years ago

In Python, classes cannot be creating with hyphens, and some front end frameworks such as Vue.js require them.

See here: https://vuetifyjs.com/en/getting-started/quick-start

This necessitates specifying a tagname attribute for each custom tag containing a hyphen, which is cumbersome and repetitive.

class v_app(vue_tag):
    tagname = 'v-app'

class v_content(vue_tag):
    tagname = 'v-content'

class v_container(vue_tag):
    tagname = 'v-container'

...

Perhaps the html_tag element could have a property such as hyphenate_tagname that would replace underscores with hyphens during rendering? Then the problem could be solved like so:

class vue_tag(html_tag):
    hyphenate_tagname = True

class v_app(vue_tag):
    pass

class v_content(vue_tag):
    pass

class v_container(vue_tag):
    pass

...
Knio commented 4 years ago

I'm not really interested in adding a flag for such a specific feature or to support a specific JS framework.

Here is a snippet to do what you want without support from the library:

import dominate

class tag_hyphenate(type):
  def __new__(cls, name, bases, dict):
    return type.__new__(cls, name.replace('_', '-'), bases, dict)
class vue_tag(dominate.dom_tag.dom_tag, metaclass=tag_hyphenate): pass

class v_app(vue_tag): pass
class v_content(vue_tag): pass
class v_container(vue_tag): pass

o = v_app(v_content(v_container('hello world')))
print(o.render())
<v-app>
  <v-content>
    <v-container>hello world</v-container>
  </v-content>
</v-app>

https://repl.it/repls/RightToughDriver