在小部件的代码中,我需要访问渲染元素的 HTML id。我知道我可以对呈现的字符串运行正则表达式并获取 ID,但我相信一定有一种简单的方法。
假设这是我拥有的小部件:
class TextInputWithHint(TextInput):
...
def render(self, name, value, attrs):
res = super(TextInputWithHint, self).render(name, value, attrs = attrs)
res += mark_safe(u'<script type="text/javascript">alert(%s)</script>' \
% self.attrs['id'])
return res
除了 self.attrs['id']
不起作用。
这里有获取ID的简单方法吗?
谢谢!
最佳答案
对于您的用例,您可以在传递给 render()
的 attrs
参数中找到 id
属性。在尝试使用它之前检查它是否存在是个好主意:
def render(self, name, value, attrs=None):
# ...
if attrs and 'id' in attrs:
# Use attrs['id']
关于html - Django 小部件 HTML id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/863414/