Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/xblock_discussion/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ class DiscussionAppConfig(AppConfig):
dynamically injects this module into `INSTALLED_APPS` at runtime.

This automatically exposes our `templates/` directory to the platform natively
without manual intervention.
without manual intervention. It also makes our `templatetags/` package loadable, which
the templates need for `{% load xblock_i18n %}`, the tags that translate through the
block's i18n service.

References:

Expand Down
23 changes: 19 additions & 4 deletions src/xblock_discussion/block.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@
from xblock.completable import XBlockCompletionMode
from xblock.core import XBlock
from xblock.fields import UNIQUE_ID, Scope, String
from xblock.utils.resources import ResourceLoader
from xblock.utils.studio_editable import StudioEditableXBlockMixin

from xblocks_core.legacy_utils.xml_utils import LegacyXmlMixin

log = logging.getLogger(__name__)
loader = ResourceLoader(__name__)

# Where the ``{% load xblock_i18n %}`` template tags look for the block's i18n service.
I18N_SERVICE_CONTEXT_KEY = "_i18n_service"
Text = markupsafe.escape # pylint: disable=invalid-name


Expand Down Expand Up @@ -154,6 +155,9 @@ def student_view(self, context=None):
if not self.is_visible:
return fragment

# Translate with this block's own catalog. The module-level ``_`` only marks strings.
_ = self.runtime.service(self, "i18n").gettext

self.add_resource_urls(fragment)
login_msg = ""

Expand Down Expand Up @@ -196,7 +200,7 @@ def student_view(self, context=None):
"PLATFORM_NAME": settings.PLATFORM_NAME,
"enable_discussion_home_panel": settings.FEATURES.get("ENABLE_DISCUSSION_HOME_PANEL", False),
}
fragment.add_content(render_to_string("discussion_templates/_discussion_inline.html", context))
fragment.add_content(self._render_template("discussion_templates/_discussion_inline.html", context))

fragment.initialize_js("DiscussionInlineBlock")

Expand All @@ -211,9 +215,20 @@ def author_view(self, context=None):
"discussion_id": self.discussion_id,
"is_visible": self.is_visible,
}
fragment.add_content(loader.render_django_template("templates/_discussion_inline_studio.html", context))
fragment.add_content(self._render_template("discussion_templates/_discussion_inline_studio.html", context))
return fragment

def _render_template(self, template_name, context):
"""
Render one of this block's Django templates, found through the ``xblock_discussion`` Django app.

Their ``{% load xblock_i18n %}`` tags translate through this block's i18n service, so the strings
come from the block's own catalog rather than Django's global one.
"""
return render_to_string(
template_name, {**context, I18N_SERVICE_CONTEXT_KEY: self.runtime.service(self, "i18n")}
)

def student_view_data(self):
"""
Returns a JSON representation of the student_view of this XBlock.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% load i18n %}
{% load xblock_i18n %}

{% include "discussion_templates/_underscore_templates.html" %}
{% include "discussion_templates/_thread_list_template.html" %}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% load i18n %}
{% load xblock_i18n %}

<div class="discussion-module" data-discussion-id="{{ discussion_id }}">
<p>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% load i18n %}
{% load xblock_i18n %}

<script type="text/template" id="thread-list-template">
<div class="forum-nav-thread-list-wrapper" id="sort-filter-wrapper" tabindex="-1">
Expand Down
3 changes: 3 additions & 0 deletions src/xblock_discussion/templatetags/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""
Template tag libraries for this Django app.
"""
10 changes: 10 additions & 0 deletions src/xblock_discussion/templatetags/xblock_i18n.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""
``{% load xblock_i18n %}``: ``trans`` and ``blocktrans`` that translate through the XBlock i18n service.

This is the XBlock library ``xblock.utils.templatetags.i18n``, made loadable by name. Django only finds
tag libraries inside installed apps' ``templatetags`` packages, and the ``xblock`` package is not an app.

The tags look for the block's i18n service under the ``_i18n_service`` key of the template context.
"""

from xblock.utils.templatetags.i18n import register # noqa: F401
58 changes: 58 additions & 0 deletions src/xblock_discussion/tests/test_discussion.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
from unittest import TestCase, mock

import ddt
from django.test import override_settings
from lxml import etree
from xblock.field_data import DictFieldData
from xblock.fields import NO_CACHE_VALUE, UNIQUE_ID, ScopeIds
from xblock.runtime import Runtime

from xblock_discussion import DiscussionXBlock
from xblocks_core.tests.i18n import FakeI18nService


def attribute_pair_repr(self):
Expand Down Expand Up @@ -180,3 +182,59 @@ def test_export_custom_discussion_id(self, discussion_id):
block.add_xml_to_node(target_node)
assert target_node.tag == "discussion"
assert target_node.attrib["discussion_id"], discussion_id


class DiscussionXBlockI18nTests(TestCase):
"""
The block's views translate through its own i18n service, not Django's global catalog.
"""

def setUp(self):
super().setUp()
self.i18n_service = FakeI18nService(
{
"Show Discussion": "MOSTRAR DISCUSION",
"Discussion": "DISCUSION",
"sign in": "INICIAR SESION",
"Show all posts": "MOSTRAR TODO",
"To view live discussions, click Preview or View Live in Unit Settings.": "VISTA PREVIA",
}
)
self.discussion_config = mock.Mock()
self.discussion_config.is_discussion_visible.return_value = True
self.discussion_config.is_discussion_enabled = True
self.discussion_config.has_permission.return_value = True
self.user = mock.Mock(is_authenticated=False)
services = {
"i18n": self.i18n_service,
"discussion_config_service": self.discussion_config,
"user": mock.Mock(_django_user=self.user),
}
self.runtime = mock.Mock(spec=Runtime)
self.runtime.service = mock.Mock(side_effect=lambda _block, name: services.get(name))
self.runtime.local_resource_url = mock.Mock(return_value="/static/resource")
keys = ScopeIds("any_user", "discussion", "def_id", "usage_id")
self.block = DiscussionXBlock(self.runtime, scope_ids=keys, field_data=DictFieldData({}))

@override_settings(PLATFORM_NAME="Test", FEATURES={})
@mock.patch("xblock_discussion.block.reverse", return_value="/login")
def test_student_view_uses_block_catalog(self, _reverse):
"""The inline template, the partials it includes, and the sign-in message use the block catalog."""
html = self.block.student_view().content

assert "MOSTRAR DISCUSION" in html
assert "Show Discussion" not in html
assert "DISCUSION" in html # the default display name, via _()
assert "INICIAR SESION" in html
assert ">sign in<" not in html
assert "MOSTRAR TODO" in html # from _thread_list_template.html
assert 'id="thread-list-template"' in html
assert "window.PLATFORM_NAME" in html # from _underscore_templates.html
assert 'type="text/template"' in html # from templates.underscore

def test_author_view_uses_block_catalog(self):
"""The studio template is rendered with the block's i18n service."""
html = self.block.author_view().content

assert "VISTA PREVIA" in html
assert "click Preview" not in html
24 changes: 20 additions & 4 deletions src/xblock_problem/block.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@

log = logging.getLogger("edx.courseware")

# Where the ``{% load xblock_i18n %}`` template tags look for the block's i18n service.
I18N_SERVICE_CONTEXT_KEY = "_i18n_service"


# Make '_' a no-op so we can scrape strings. Using function instead of
# `django.utils.translation.gettext_noop` because Django cannot be imported in this file
Expand Down Expand Up @@ -418,6 +421,19 @@ def _add_i18n_js_catalog(self, fragment):
if url:
fragment.add_javascript_url(url)

def _render_template(self, template_name, context):
"""
Render one of this block's Django templates (``problem.html``, the capa input templates, ...).

They live under ``capa/templates/xblock_problem/`` and are found through the ``xblock_problem.capa``
Django app. Their ``{% load xblock_i18n %}`` tags translate through this block's i18n service, so
the strings come from the block's own catalog rather than Django's global one.
"""
return render_to_string(
f"xblock_problem/{template_name}",
{**context, I18N_SERVICE_CONTEXT_KEY: self.runtime.service(self, "i18n")},
)

def student_view(self, _context, show_detailed_errors=False):
"""
Return the student view.
Expand Down Expand Up @@ -918,7 +934,7 @@ def new_lcp(self, state, text=None):
get_python_lib_zip=sandbox_service.get_python_lib_zip,
DEBUG=self.debug,
i18n=self.runtime.service(self, "i18n"),
render_template=render_to_string,
render_template=self._render_template,
resources_fs=self.runtime.resources_fs,
seed=seed, # Why do we do this if we have self.seed?
xqueue=None if is_studio else xqueue_service,
Expand Down Expand Up @@ -1020,7 +1036,7 @@ def get_html(self):
"""
curr_score, total_possible = self.get_display_progress()

return render_to_string(
return self._render_template(
"problem_ajax.html",
{
"element_id": self.usage_key.html_id(),
Expand Down Expand Up @@ -1369,7 +1385,7 @@ def get_problem_html(self, encapsulate=True, submit_notification=False): # pyli
"submit_disabled_cta": submit_disabled_ctas[0] if submit_disabled_ctas else None,
}

html = render_to_string("problem.html", context)
html = self._render_template("problem.html", context)

if encapsulate:
html = HTML('<div id="problem_{id}" class="problem" data-url="{ajax_url}">{html}</div>').format(
Expand Down Expand Up @@ -1654,7 +1670,7 @@ def get_answer(self, _data):

return {
"answers": new_answers,
"correct_status_html": render_to_string(
"correct_status_html": self._render_template(
"status_span.html",
{"status": Status("correct", self.runtime.service(self, "i18n").gettext)},
),
Expand Down
7 changes: 6 additions & 1 deletion src/xblock_problem/capa/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,12 @@ class CapaAppConfig(AppConfig):
dynamically injects this module into `INSTALLED_APPS` at runtime.

This automatically exposes our `templates/` directory to the platform natively
without manual intervention.
without manual intervention. It also makes our `templatetags/` package loadable, which
the templates need for `{% load xblock_i18n %}`, the tags that translate through the
block's i18n service.

The same applies to our `static/` directory: Django's staticfiles finder only collects
static files from installed apps.

References:

Expand Down
2 changes: 1 addition & 1 deletion src/xblock_problem/capa/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def render_template(self, template_filename, dictionary):
"""
Render the specified template with the given dictionary of context data.
"""
return get_template(template_filename).render(dictionary)
return get_template(f"xblock_problem/{template_filename}").render(dictionary)


def main():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
{% if option.choice == status.classname and status == status.classname %}
<span class="tag-status {{ status.classname }}"
aria-describedby="input_{{ id }}_comment">
{% include "status_span.html" with status=status %}
{% include "xblock_problem/status_span.html" with status=status %}
</span>
{% endif %}
{% endif %}
Expand Down Expand Up @@ -54,7 +54,7 @@
id="input_{{ id }}"
value="{{ value }}" />
{% endif %}
{% include "status_span.html" with status=status status_id=id %}
{% include "xblock_problem/status_span.html" with status=status status_id=id %}
<p id="answer_{{ id }}" class="answer answer-annotation"></p>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
{% if size %}size="{{ size }}"{% endif %} />
<p class="indicator-container">
{{ value }}
{% include "status_span.html" with status=status status_id=id %}
{% include "xblock_problem/status_span.html" with status=status status_id=id %}
</p>
<div id="input_{{ id }}_preview" class="equation"></div>
<p id="answer_{{ id }}" class="answer"></p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@
</fieldset>
<div class="indicator-container">
{% if show_correctness != 'never' %}
{% include "status_span.html" with status=status status_id=id %}
{% include "xblock_problem/status_span.html" with status=status status_id=id %}
{% else %}
{% include "status_span.html" with status=status status_id=id hide_correctness=True %}
{% include "xblock_problem/status_span.html" with status=status status_id=id hide_correctness=True %}
{% endif %}
</div>
{% if show_correctness == "never" %}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% load i18n %}
{% load xblock_i18n %}
{% load static %}
{% with element_checked=False %}
{% for choice_id, _ in choices %}
Expand Down Expand Up @@ -49,7 +49,7 @@
value="{{ value }}" />
<div class="indicator-container">
{% if input_type == 'checkbox' or not value or status.classname == 'incomplete' or status.classname == 'unsubmitted' or status.classname == 'unanswered' %}
{% include "status_span.html" with status=status status_id=id %}
{% include "xblock_problem/status_span.html" with status=status status_id=id %}
{% endif %}
</div>
{% if show_correctness == "never" %}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% load i18n %}
{% load xblock_i18n %}
<div id="textbox_{{ id }}" class="capa_inputtype textbox cminput">
{% if response_data.label %}
<label class="problem-group-label" for="cm-textarea-{{ id }}">{{ response_data.label }}</label>
Expand All @@ -21,7 +21,7 @@
<span class="cm-editor-exit-message capa-message"
id="cm-editor-exit-message-{{ id }}">{{ code_mirror_exit_message }}</span>
<div class="grader-status" tabindex="-1">
{% include "status_span.html" with status=status status_id=id %}
{% include "xblock_problem/status_span.html" with status=status status_id=id %}
{% if status == 'queued' %}<span style="display:none;" class="xqueue" id="{{ id }}">{{ queue_len }}</span>{% endif %}
{% if hidden %}<div style="display:none;" name="{{ hidden }}" inputid="input_{{ id }}" />{% endif %}
<p class="debug">{{ status.display_name }}</p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
id="input_{{ id }}"
value="{{ value }}"
style="display:none" />
{% include "status_span.html" with status=status status_id=id %}
{% include "xblock_problem/status_span.html" with status=status status_id=id %}
<p id="answer_{{ id }}" class="answer"></p>
{% if msg %}<span class="message" tabindex="-1">{{ msg|safe }}</span>{% endif %}
{% if status == 'unsubmitted' or status == 'correct' or status == 'incorrect' or status == 'partially-correct' or status == 'incomplete' %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
id="input_{{ id }}"
aria-describedby="answer_{{ id }}"
value="{{ value }}" />
{% include "status_span.html" with status=status status_id=id %}
{% include "xblock_problem/status_span.html" with status=status status_id=id %}
<p id="answer_{{ id }}" class="answer"></p>
{% if status == 'unsubmitted' or status == 'correct' or status == 'incorrect' or status == 'partially-correct' or status == 'incomplete' %}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
value="{{ value }}"
style="display:none" />
<p class="indicator-container drag-and-drop--status"
aria-describedby="input_{{ id }}">{% include "status_span.html" with status=status status_id=id %}</p>
aria-describedby="input_{{ id }}">{% include "xblock_problem/status_span.html" with status=status status_id=id %}</p>
<p id="answer_{{ id }}" class="answer"></p>
{% if msg %}<span class="message" tabindex="-1">{{ msg|safe }}</span>{% endif %}
{% if status == 'unsubmitted' or status == 'correct' or status == 'incorrect' or status == 'partially-correct' or status == 'incomplete' %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
id="input_{{ id }}"
value="{{ value }}" />
<p class="indicator-container" aria-describedby="input_{{ id }}">
{% include "status_span.html" with status=status status_id=id %}
{% include "xblock_problem/status_span.html" with status=status status_id=id %}
</p>
<p id="answer_{{ id }}" class="answer"></p>
{% if status == 'unsubmitted' or status == 'correct' or status == 'incorrect' or status == 'partially-correct' or status == 'incomplete' %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<button id="reset_{{ id }}" class="reset">Reset</button>
<p id="answer_{{ id }}" class="answer"></p>
<p class="indicator-container" aria-describedby="input_{{ id }}">
{% include "status_span.html" with status=status status_id=id %}
{% include "xblock_problem/status_span.html" with status=status status_id=id %}
</p>
<div class="error_message"
style="padding: 5px 5px 5px 5px;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
{{ describedby_html }}
{% if size %}size="{{ size }}"{% endif %} />
<span class="trailing_text" id="trailing_text_{{ id }}">{{ trailing_text }}</span>
{% include "status_span.html" with status=status status_id=id %}
{% include "xblock_problem/status_span.html" with status=status status_id=id %}
<p id="answer_{{ id }}" class="answer"></p>
<div id="input_{{ id }}_preview" class="equation">
\(\)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,5 @@
top: 0"></div>
</div>
<script type="text/javascript" charset="utf-8">(new ImageInput('{{ id }}'));</script>
{% include "status_span.html" with status=status status_id=id %}
{% include "xblock_problem/status_span.html" with status=status status_id=id %}
</div>
Loading
Loading