【问题标题】:If-else and for loops not working in HTML for new XBlock in OpenEdX对于 OpenEdX 中的新 XBlock,if-else 和 for 循环在 HTML 中不起作用
【发布时间】:2021-01-29 16:13:33
【问题描述】:

我创建了一个新的 XBLock 并尝试将数据从 python 文件传递​​到 HTML 文件,但是标准模板语法抛出错误,下面是 HTML 文件代码

<p>EdlyCarouselXBlock: count is now
    <span class='count'>{self.count}</span> (click me to increment).
    {{ self.count }}
    {% if self.count%}
    <p>Simple If</p>
    {%endif%}
</p>
<p id="decrement">(click me to Decrement).</p>
</div>

它支持单个括号来访问值 {self.name},for 循环和 if-else 会引发错误。尝试使用 python 3.6.5 和 3.8.0,两个版本上的相同问题,任何帮助将不胜感激,lms/cms 中也有相同的问题。

【问题讨论】:

    标签: django-templates openedx


    【解决方案1】:

    解决问题,发布解决方案以供将来参考。 默认 xblock 是不使用 Django 模板创建的,所以我们需要手动配置它。

    添加了默认student_view功能

    def student_view(self, context=None):
        """
        The primary view of the SampleXBlock, shown to students
        when viewing courses.
        """
        html = self.resource_string("static/html/sample.html")
        frag = Fragment(html.format(self=self))
        frag.add_css(self.resource_string("static/css/sample.css"))
        frag.add_javascript(self.resource_string("static/js/src/sample.js"))
        frag.initialize_js('SampleXBlock')
        return frag
    

    所以为了涉及 Django 模板渲染,请进行以下更改。 包括模板和上下文

    from django.template import Context, Template

    # Add this method in your xblock class
    
    def render_template(self, template_path, context={}):
        template_str = self.resource_string(template_path)
        template = Template(template_str)
        return template.render(Context(context))
    
    def student_view(self, context=None):
        """
        The primary view of the SampleXBlock, shown to students
        when viewing courses.
        """
        frag = Fragment()
    
        html = self.render_template("static/html/sample.html", {'count': self.count})
        frag.add_content(html)
        frag.add_css(self.resource_string("static/css/sample.css"))
        frag.add_javascript(self.resource_string("static/js/src/sample.js"))
        frag.initialize_js('SampleXBlock')
        return frag
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 2017-08-02
      • 2019-12-04
      • 2021-11-24
      • 2022-01-10
      • 2018-04-14
      • 1970-01-01
      相关资源
      最近更新 更多