使用“类”作为 Mako 宏的一个选项

发布于 2024-12-10 07:03:51 字数 984 浏览 0 评论 0原文

我正在编写一个 Mako 扩展来帮助渲染表单。我取得了巨大的进步,直到我遇到了关于 css 类的一大障碍。我想编写如下所示的代码:

<%fp:form method="post" action="" class="css-class"%>
...content
</%fp:form>

fp:form 引用的函数看起来就像这样:

@supports_caller
def form(context, **kwargs):
     #...

当我运行此代码时,我收到以下异常:

SyntaxException: (SyntaxError) invalid syntax (<unknown>, line 1) (u"fp.form(method=u'post',action=u'',class=u'css-class')") at line: 1 char: 52

仅当指定“class”属性时才会发生这种情况,大概是因为 Mako 是将属性直接转换为关键字参数,而不是字典解包。我尝试向我的函数传递一个特殊的“attrs”参数,但似乎没有好的方法将字典传递给 Mako:

<%fp:form method="post" action="" attrs="${{'class':'css-class'}}"%>
#SyntaxError: invalid syntax
<%fp:form method="post" action="" attrs="${dict(class='css-class')}"%>
#Won't work - can't pass 'class' directly as a keyword argument!

那么我该如何解决这个问题呢?我知道我可以指定一个特殊的属性,例如“css_class”并将其转换为类,但这有点麻烦,并进一步阻止库每次生成带有 css_class 属性的表单。

I am writing a Mako extension that assist in rendering forms. I was making excellent progress until I ran into one big stumbling block regarding css classes. I want to write code that looks like this:

<%fp:form method="post" action="" class="css-class"%>
...content
</%fp:form>

The function that fp:form refers to looks simply like:

@supports_caller
def form(context, **kwargs):
     #...

When I run this code, I get the following exception:

SyntaxException: (SyntaxError) invalid syntax (<unknown>, line 1) (u"fp.form(method=u'post',action=u'',class=u'css-class')") at line: 1 char: 52

This only happens when the "class" attribute is specified, presumably because Mako is converting the attributes directly to keyword arguments rather than dictionary unpacking. I tried passing a special "attrs" argument to my function, but there seems to be no good way to pass a dict to Mako:

<%fp:form method="post" action="" attrs="${{'class':'css-class'}}"%>
#SyntaxError: invalid syntax
<%fp:form method="post" action="" attrs="${dict(class='css-class')}"%>
#Won't work - can't pass 'class' directly as a keyword argument!

So how do I get around this? I know I can specify a special attribute, like "css_class" and convert that into class, but that's a bit of a hack and further prevents the library from every producing a form with an attribute with css_class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

欲拥i 2024-12-17 07:03:51

没有办法解决这个问题,因为 class 是一个关键字,并且总是这样解析。人们通常使用 class_ 来代替。

There is no way around this because class is a keyword and is always parsed as such. People usually use class_ instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文