lxml-ElementMaker:添加属性

时间:2018-09-03 21:41:52

标签: python xml lxml

让我们假设以下代码段:

page = (
    E.html(
        E.head(
            E.title("This is a sample document")
        ),
        E.body(
            E.h1("Hello!", CLASS("title")),
            E.p("This is a paragraph with ", B("bold"), " text in it!"),
            E.p("This is another paragraph, with a ",
                A("link", href="http://www.python.org"), "."),
            E.p("Here are some reserved characters: <spam&egg>."),
            ET.XML("<p>And finally, here is an embedded XHTML fragment.</p>"),
        )
    )
)

来源:https://lxml.de/api/lxml.builder.ElementMaker-class.html

如何使用上述语法向<body>标签添加属性? 做这样的事情:

E.body(myattr="something", 

无法解决我的问题。所以任何提示都欢迎!

1 个答案:

答案 0 :(得分:1)

我认为您可以如下定义一个新函数:

E.body(ATTR('myattr', "something"),
    E.h1("Hello!", CLASS("title")),
    ...         

并在E.body中使用它,如下所示:

....

<script id="template" type="text/x-handlebars-template">
       ....
      @if (CurrentUserRepository.IsInRoleEnums(RoleEnum.TPS_Administrator)) 
           {
               <i class="fas fa-trash-alt text-dark pointer" title="Delete this item" onclick="DeleteNotification({{NotificationId}})"></i>
           }
       else
           {
              //handlebars shown below doesn't work
              {{#if UserCanSetClosed}}
                 <i class="fas fa-trash-alt text-dark pointer" title="Delete this item" onclick="DeleteNotification({{NotificationId}})"></i>
              {{/if}}                    
           }
</script>

希望这可以解决您的问题。