예제 #1
0
    def _staff_view(self, context):
        """
        Render the staff view for a split test module.
        """
        fragment = Fragment()
        active_contents = []
        inactive_contents = []

        for child_location in self.children:  # pylint: disable=no-member
            child_descriptor = self.get_child_descriptor_by_location(
                child_location)
            child = self.system.get_module(child_descriptor)
            rendered_child = child.render(STUDENT_VIEW, context)
            fragment.add_fragment_resources(rendered_child)
            group_name, updated_group_id = self.get_data_for_vertical(child)

            if updated_group_id is None:  # inactive group
                group_name = child.display_name
                updated_group_id = [
                    g_id for g_id, loc in self.group_id_to_child.items()
                    if loc == child_location
                ][0]
                inactive_contents.append({
                    'group_name':
                    _(u'{group_name} (inactive)').format(
                        group_name=group_name),
                    'id':
                    text_type(child.location),
                    'content':
                    rendered_child.content,
                    'group_id':
                    updated_group_id,
                })
                continue

            active_contents.append({
                'group_name': group_name,
                'id': text_type(child.location),
                'content': rendered_child.content,
                'group_id': updated_group_id,
            })

        # Sort active and inactive contents by group name.
        sorted_active_contents = sorted(active_contents,
                                        key=itemgetter('group_name'))
        sorted_inactive_contents = sorted(inactive_contents,
                                          key=itemgetter('group_name'))

        # Use the new template
        fragment.add_content(
            self.system.render_template(
                'split_test_staff_view.html', {
                    'items': sorted_active_contents + sorted_inactive_contents,
                }))
        fragment.add_css('.split-test-child { display: none; }')
        fragment.add_javascript_url(
            self.runtime.local_resource_url(self,
                                            'public/js/split_test_staff.js'))
        fragment.initialize_js('ABTestSelector')
        return fragment
    def student_view(self, context):
        """
        Player view, displayed to the student
        """

        fragment = Fragment()
        fragment.add_content(
            loader.render_django_template('/templates/html/drag_and_drop.html',
                                          i18n_service=self.i18n_service))
        css_urls = ('public/css/drag_and_drop.css', )
        js_urls = [
            'public/js/vendor/virtual-dom-1.3.0.min.js',
            'public/js/drag_and_drop.js',
        ]

        statici18n_js_url = self._get_statici18n_js_url()
        if statici18n_js_url:
            js_urls.append(statici18n_js_url)

        for css_url in css_urls:
            fragment.add_css_url(self.runtime.local_resource_url(
                self, css_url))
        for js_url in js_urls:
            fragment.add_javascript_url(
                self.runtime.local_resource_url(self, js_url))

        self.include_theme_files(fragment)

        fragment.initialize_js('DragAndDropBlock', self.student_view_data())

        return fragment
예제 #3
0
    def student_view_aside(self, block, context):  # pylint: disable=unused-argument
        """
        Display the tag selector with specific categories and allowed values,
        depending on the context.
        """
        if isinstance(block, CapaModule):
            tags = []
            for tag in self.get_available_tags():
                tag_available_values = tag.get_values()
                tag_current_values = self.saved_tags.get(tag.name, [])

                if isinstance(tag_current_values, basestring):
                    tag_current_values = [tag_current_values]

                tag_values_not_exists = [cur_val for cur_val in tag_current_values
                                         if cur_val not in tag_available_values]

                tag_values_available_to_choose = tag_available_values + tag_values_not_exists
                tag_values_available_to_choose.sort()

                tags.append({
                    'key': tag.name,
                    'title': tag.title,
                    'values': tag_values_available_to_choose,
                    'current_values': tag_current_values,
                })
            fragment = Fragment(render_to_string('structured_tags_block.html', {'tags': tags,
                                                                                'tags_count': len(tags),
                                                                                'block_location': block.location}))
            fragment.add_javascript_url(self._get_studio_resource_url('/js/xblock_asides/structured_tags.js'))
            fragment.initialize_js('StructuredTagsInit')
            return fragment
        else:
            return Fragment(u'')
예제 #4
0
 def student_view(self, _context):
     """
     Return a fragment that contains the html for the student view
     """
     fragment = Fragment(self.get_html())
     fragment.add_javascript_url(settings.STATIC_URL + 'bundles/commons.js')
     return fragment
예제 #5
0
    def mentoring_view(self, context=None):
        """ Render this XBlock within a mentoring block. """
        context = context.copy() if context else {}
        student_submissions_key = context.get('student_submissions_key')
        context['title'] = self.display_name
        context['description'] = self.description
        if student_submissions_key:
            location = self.location.replace(
                branch=None,
                version=None)  # Standardize the key in case it isn't already
            target_key = {
                'student_id': student_submissions_key,
                'course_id': str(location.course_key),
                'item_id': self.name,
                'item_type': 'pb-answer',
            }
            submissions = sub_api.get_submissions(target_key, limit=1)
            try:
                context['student_input'] = submissions[0]['answer']
            except IndexError:
                context['student_input'] = None
        else:
            context['student_input'] = self.student_input
        html = loader.render_django_template(
            'templates/html/answer_read_only.html',
            context,
            i18n_service=self.i18n_service)

        fragment = Fragment(html)
        fragment.add_css_url(
            self.runtime.local_resource_url(self, self.css_path))
        fragment.add_javascript_url(
            self.runtime.local_resource_url(self, 'public/js/answer_recap.js'))
        fragment.initialize_js('AnswerRecapBlock')
        return fragment
예제 #6
0
    def student_view_aside(self, block, context):  # pylint: disable=unused-argument
        """
        Display the tag selector with specific categories and allowed values,
        depending on the context.
        """
        if isinstance(block, ProblemBlock):
            tags = []
            for tag in self.get_available_tags():
                tag_available_values = tag.get_values()
                tag_current_values = self.saved_tags.get(tag.name, [])

                if isinstance(tag_current_values, six.string_types):
                    tag_current_values = [tag_current_values]

                tag_values_not_exists = [cur_val for cur_val in tag_current_values
                                         if cur_val not in tag_available_values]

                tag_values_available_to_choose = tag_available_values + tag_values_not_exists
                tag_values_available_to_choose.sort()

                tags.append({
                    'key': tag.name,
                    'title': tag.title,
                    'values': tag_values_available_to_choose,
                    'current_values': tag_current_values,
                })
            fragment = Fragment(render_to_string('structured_tags_block.html', {'tags': tags,
                                                                                'tags_count': len(tags),
                                                                                'block_location': block.location}))
            fragment.add_javascript_url(self._get_studio_resource_url('/js/xblock_asides/structured_tags.js'))
            fragment.initialize_js('StructuredTagsInit')
            return fragment
        else:
            return Fragment(u'')
예제 #7
0
    def student_view(self, context=None):
        """
        Create a fragment used to display the XBlock to a student.
        `context` is a dictionary used to configure the display (unused).

        Returns a `Fragment` object specifying the HTML, CSS, and JavaScript
        to display.
        """

        self.href = "https://vimeo.com/46100581"
        self.maxwidth = 800
        self.maxheight = 600

        provider, embed_code = self.get_embed_code_for_url(self.href)

        # Load the HTML fragment from within the package and fill in the template
        html_str = pkg_resources.resource_string(
            __name__, "static/html/simplevideo.html")
        frag = Fragment(str(html_str).format(self=self, embed_code=embed_code))
        # Load CSS
        css_str = pkg_resources.resource_string(__name__,
                                                "static/css/simplevideo.css")
        frag.add_css(str(css_str))
        # Load JS
        if provider == 'vimeo.com':
            # Load the Froogaloop library from vimeo CDN.
            frag.add_javascript_url("//f.vimeocdn.com/js/froogaloop2.min.js")
            js_str = pkg_resources.resource_string(
                __name__, "static/js/src/simplevideo.js")
            frag.add_javascript(str(js_str))
            frag.initialize_js('SimpleVideoBlock')
        return frag
    def student_view(self, context):
        """ Renders parameters to template. """
        context = {
            'course_key': self.runtime.course_id,
            'display_name': self.display_name_with_default_escaped,
            'tag': self.instructor_tags,
            'source': self.source,
            'instructions_html': self.instructions,
            'content_html': self.content,
            'token': retrieve_token(self.user_email, self.annotation_token_secret),
            'diacritic_marks': self.diacritics,
            'annotation_storage': self.annotation_storage_url,
            'default_tab': self.default_tab,
            'instructor_email': self.instructor_email,
            'annotation_mode': self.annotation_mode,
            'is_course_staff': self.is_course_staff,
        }
        fragment = Fragment(self.system.render_template('textannotation.html', context))

        # TinyMCE already exists in Studio so we should not load the files again
        # get_real_user always returns "None" in Studio since its runtimes contains no anonymous ids
        if self.runtime.get_real_user is not None:
            fragment.add_javascript_url(self.runtime.STATIC_URL + "js/vendor/tinymce/js/tinymce/tinymce.full.min.js")
            fragment.add_javascript_url(self.runtime.STATIC_URL + "js/vendor/tinymce/js/tinymce/jquery.tinymce.min.js")
        return fragment
예제 #9
0
    def student_view(self, context=None):
        """
        The primary view of the CodeSnippetXBlock, shown to students
        when viewing courses.
        """
        frag = Fragment()
        frag.content = loader.render_django_template(
            'templates/code_snippet.html', self._get_context())
        frag.add_css(self.resource_string("static/css/code_snippet.css"))
        frag.add_css_url(
            "//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.3.2/styles/agate.min.css"
        )

        logger.info("{}".format(self._get_context()))

        # Add i18n js
        statici18n_js_url = self._get_statici18n_js_url()
        if statici18n_js_url:
            frag.add_javascript_url(
                self.runtime.local_resource_url(self, statici18n_js_url))

        frag.add_javascript(
            self.resource_string("static/js/src/code_snippet.js"))
        frag.add_javascript_url(
            "//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.3.2/highlight.min.js"
        )
        frag.initialize_js('CodeSnippetXBlock', self._get_context())
        return frag
    def author_view(self, context):
        """
        Renders the Studio views.
        Normal studio view: If block is properly configured, displays library status summary
        Studio container view: displays a preview of all possible children.
        """
        fragment = Fragment()
        root_xblock = context.get('root_xblock')
        is_root = root_xblock and root_xblock.location == self.location

        if is_root:
            # User has clicked the "View" link. Show a preview of all possible children:
            if self.children:  # pylint: disable=no-member
                fragment.add_content(
                    self.system.render_template(
                        "library-block-author-preview-header.html", {
                            'max_count': self.max_count,
                            'display_name': self.display_name or self.url_name,
                        }))
                context['can_edit_visibility'] = False
                context['can_move'] = False
                self.render_children(context,
                                     fragment,
                                     can_reorder=False,
                                     can_add=False)
        # else: When shown on a unit page, don't show any sort of preview -
        # just the status of this block in the validation area.

        # The following JS is used to make the "Update now" button work on the unit page and the container view:
        fragment.add_javascript_url(
            self.runtime.local_resource_url(
                self, 'public/js/library_content_edit.js'))
        fragment.initialize_js('LibraryContentAuthorView')
        return fragment
    def studio_view(self, context):
        """
        Render a form for editing this XBlock
        """
        fragment = Fragment()
        static_content = ResourceLoader(
            'common.djangoapps.pipeline_mako').load_unicode(
                'templates/static_content.html')
        render_react = MakoTemplate(static_content,
                                    default_filters=[]).get_def('renderReact')
        react_content = render_react.render(
            component="LibrarySourcedBlockPicker",
            id="library-sourced-block-picker",
            props={
                'selectedXblocks': self.source_block_ids,
            })
        fragment.content = loader.render_django_template(
            'templates/library-sourced-block-studio-view.html', {
                'react_content': react_content,
                'save_url': self.runtime.handler_url(self,
                                                     'submit_studio_edits'),
            })

        fragment.add_javascript_url(
            self.runtime.local_resource_url(
                self, 'public/js/library_source_block.js'))
        fragment.initialize_js('LibrarySourceBlockStudioView')

        return fragment
    def author_view(self, context):
        """
        Renders the Studio views.
        Normal studio view: If block is properly configured, displays library status summary
        Studio container view: displays a preview of all possible children.
        """
        fragment = Fragment()
        root_xblock = context.get('root_xblock')
        is_root = root_xblock and root_xblock.location == self.location

        if is_root:
            # User has clicked the "View" link. Show a preview of all possible children:
            if self.children:  # pylint: disable=no-member
                fragment.add_content(self.system.render_template("library-block-author-preview-header.html", {
                    'max_count': self.max_count,
                    'display_name': self.display_name or self.url_name,
                }))
                context['can_edit_visibility'] = False
                context['can_move'] = False
                self.render_children(context, fragment, can_reorder=False, can_add=False)
        # else: When shown on a unit page, don't show any sort of preview -
        # just the status of this block in the validation area.

        # The following JS is used to make the "Update now" button work on the unit page and the container view:
        fragment.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/library_content_edit.js'))
        fragment.initialize_js('LibraryContentAuthorView')
        return fragment
예제 #13
0
    def student_view(self, context=None):
        """
        The primary view of the EdflexXBlock, shown to students
        when viewing courses.
        """
        if context is None:
            context = {}

        context.update({
            'svg_sprite':
            self.resource_string('public/images/sprite.svg'),
        })

        self.update_student_context(context)
        fragment = Fragment()
        fragment.content = loader.render_django_template(
            'static/html/edflex.html', context)
        fragment.add_css(self.resource_string("static/css/edflex.css"))

        if self.resource.get('type', '') == 'video':
            fragment.add_javascript_url('https://www.youtube.com/iframe_api')

        fragment.add_javascript(
            loader.load_unicode('static/js/src/parse_duration.js'))
        fragment.add_javascript(
            self.resource_string("static/js/src/edflex.js"))
        fragment.initialize_js('EdflexXBlock')
        return fragment
예제 #14
0
    def student_view(self, context):
        """
        Renders the contents of the chosen condition for students, and all the
        conditions for staff.
        """
        if self.child is None:
            # raise error instead?  In fact, could complain on descriptor load...
            return Fragment(content="<div>Nothing here.  Move along.</div>")

        if self.system.user_is_staff:
            return self._staff_view(context)
        else:
            child_fragment = self.child.render(STUDENT_VIEW, context)
            fragment = Fragment(
                self.system.render_template(
                    'split_test_student_view.html', {
                        'child_content': child_fragment.content,
                        'child_id': self.child.scope_ids.usage_id,
                    }))
            fragment.add_fragment_resources(child_fragment)
            fragment.add_javascript_url(
                self.runtime.local_resource_url(
                    self, 'public/js/split_test_student.js'))
            fragment.initialize_js('SplitTestStudentView')
            return fragment
    def author_view(self, context):
        """
        Renders the Studio preview by rendering each child so that they can all be seen and edited.
        """
        fragment = Fragment()
        root_xblock = context.get('root_xblock')
        is_root = root_xblock and root_xblock.location == self.location
        active_groups_preview = None
        inactive_groups_preview = None

        if is_root:
            [active_children, inactive_children] = self.descriptor.active_and_inactive_children()
            active_groups_preview = self.studio_render_children(
                fragment, active_children, context
            )
            inactive_groups_preview = self.studio_render_children(
                fragment, inactive_children, context
            )

        fragment.add_content(self.system.render_template('split_test_author_view.html', {
            'split_test': self,
            'is_root': is_root,
            'is_configured': self.is_configured,
            'active_groups_preview': active_groups_preview,
            'inactive_groups_preview': inactive_groups_preview,
            'group_configuration_url': self.descriptor.group_configuration_url,
        }))
        fragment.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/split_test_author_view.js'))
        fragment.initialize_js('SplitTestAuthorView')

        return fragment
예제 #16
0
    def author_view(self, context):
        """
        Renders the Studio preview by rendering each child so that they can all be seen and edited.
        """
        fragment = Fragment()
        root_xblock = context.get('root_xblock')
        is_root = root_xblock and root_xblock.location == self.location
        active_groups_preview = None
        inactive_groups_preview = None

        if is_root:
            [active_children,
             inactive_children] = self.active_and_inactive_children()
            active_groups_preview = self.studio_render_children(
                fragment, active_children, context)
            inactive_groups_preview = self.studio_render_children(
                fragment, inactive_children, context)

        fragment.add_content(
            self.system.render_template(
                'split_test_author_view.html', {
                    'split_test': self,
                    'is_root': is_root,
                    'is_configured': self.is_configured,
                    'active_groups_preview': active_groups_preview,
                    'inactive_groups_preview': inactive_groups_preview,
                    'group_configuration_url': self.group_configuration_url,
                }))
        fragment.add_javascript_url(
            self.runtime.local_resource_url(
                self, 'public/js/split_test_author_view.js'))
        fragment.initialize_js('SplitTestAuthorView')

        return fragment
예제 #17
0
    def student_view(self, context=None):
        """
        The primary view of the GeoGebraXBlock, shown to students
        when viewing courses.
        """

	logger.info("geogebra student_view ggb_url={a}".format(a=self.ggb_url))


	"""
	Ensure that the ggb_url attribute is defined in this xblock
	"""

	ggburl = ""

	try:
                ggburl = self.ggb_url
	except NameError:
                ggburl = ""

	data = {
                "ggb_url" : ggburl
               }

        html = self.resource_string("static/html/geogebra.html")
        frag = Fragment(html.format(self=self))
        frag.add_css(self.resource_string("static/css/geogebra.css"))
        frag.add_javascript_url("https://cdn.geogebra.org/apps/deployggb.js")
        frag.add_javascript(self.resource_string("static/js/src/geogebra.js"))
        frag.initialize_js('GeoGebraXBlock',data)
        return frag
    def student_view(self, context=None):
        name = getattr(self, "unmixed_class", self.__class__).__name__

        template_path = f'templates/html/{name.lower()}.html'

        context = context.copy() if context else {}
        context['self'] = self
        context['custom_choices'] = self.custom_choices
        context['hide_header'] = context.get('hide_header',
                                             False) or not self.show_title

        fragment = Fragment(
            loader.render_django_template(template_path,
                                          context,
                                          i18n_service=self.i18n_service))
        # If we use local_resource_url(self, ...) the runtime may insert many identical copies
        # of questionnaire.[css/js] into the DOM. So we use the mentoring block here if possible.
        block_with_resources = self.get_parent()
        from .mentoring import MentoringBlock

        # We use an inline import here to avoid a circular dependency with the .mentoring module.
        if not isinstance(block_with_resources, MentoringBlock):
            block_with_resources = self
        fragment.add_css_url(
            self.runtime.local_resource_url(block_with_resources,
                                            'public/css/questionnaire.css'))
        fragment.add_javascript_url(
            self.runtime.local_resource_url(block_with_resources,
                                            'public/js/questionnaire.js'))
        fragment.add_javascript(self.get_translation_content())
        fragment.initialize_js(name)
        return fragment
예제 #19
0
    def student_view(self, context):
        """ Renders parameters to template. """
        context = {
            'course_key': self.runtime.course_id,
            'display_name': self.display_name_with_default_escaped,
            'tag': self.instructor_tags,
            'source': self.source,
            'instructions_html': self.instructions,
            'content_html': self.content,
            'token': retrieve_token(self.user_email,
                                    self.annotation_token_secret),
            'diacritic_marks': self.diacritics,
            'annotation_storage': self.annotation_storage_url,
            'default_tab': self.default_tab,
            'instructor_email': self.instructor_email,
            'annotation_mode': self.annotation_mode,
            'is_course_staff': self.is_course_staff,
        }
        fragment = Fragment(
            self.system.render_template('textannotation.html', context))

        # TinyMCE already exists in Studio so we should not load the files again
        # get_real_user always returns "None" in Studio since its runtimes contains no anonymous ids
        if self.runtime.get_real_user is not None:
            fragment.add_javascript_url(
                self.runtime.STATIC_URL +
                "js/vendor/tinymce/js/tinymce/tinymce.full.min.js")
            fragment.add_javascript_url(
                self.runtime.STATIC_URL +
                "js/vendor/tinymce/js/tinymce/jquery.tinymce.min.js")
        return fragment
예제 #20
0
    def render_to_fragment(self,
                           request,
                           course_id=None,
                           discussion_id=None,
                           thread_id=None,
                           **kwargs):
        """
        Render the discussion board to a fragment.

        Args:
            request: The Django request.
            course_id: The id of the course in question.
            discussion_id: An optional discussion ID to be focused upon.
            thread_id: An optional ID of the thread to be shown.

        Returns:
            Fragment: The fragment representing the discussion board
        """
        course_key = CourseKey.from_string(course_id)
        try:
            base_context = _create_base_discussion_view_context(
                request, course_key)
            # Note:
            #   After the thread is rendered in this fragment, an AJAX
            #   request is made and the thread is completely loaded again
            #   (yes, this is something to fix). Because of this, we pass in
            #   raise_event=False to _load_thread_for_viewing avoid duplicate
            #   tracking events.
            thread = (_load_thread_for_viewing(
                request,
                base_context['course'],
                discussion_id=discussion_id,
                thread_id=thread_id,
                raise_event=False,
            ) if thread_id else None)
            context = _create_discussion_board_context(request,
                                                       base_context,
                                                       thread=thread)
            html = render_to_string(
                'discussion/discussion_board_fragment.html', context)
            inline_js = render_to_string(
                'discussion/discussion_board_js.template', context)

            fragment = Fragment(html)
            self.add_fragment_resource_urls(fragment)
            fragment.add_javascript(inline_js)
            if not settings.REQUIRE_DEBUG:
                fragment.add_javascript_url(
                    staticfiles_storage.url(
                        'discussion/js/discussion_board_factory.js'))
            return fragment
        except cc.utils.CommentClientMaintenanceError:
            log.warning('Forum is in maintenance mode')
            html = render_to_response('discussion/maintenance_fragment.html', {
                'disable_courseware_js': True,
                'uses_pattern_library': True,
            })
            return Fragment(html)
예제 #21
0
    def student_view(self, context):
        context = context.copy() if context else {}
        fragment = Fragment()

        for child_id in self.children:
            child = self.runtime.get_block(child_id)
            # Child should be an instance of MentoringTableColumn
            child_frag = child.render('mentoring_view', context)
            fragment.add_fragment_resources(child_frag)

        context['allow_sharing'] = self.allow_sharing
        context['allow_download'] = self.allow_download
        user_service = self.runtime.service(self, 'user')
        if user_service:
            context['view_options'] = Share.objects.filter(
                shared_with__username=self.current_user_key,
                block_id=self.block_id,
            ).values_list('shared_by__username', flat=True)
            context['username'] = self.current_user_key
            share_notifications = Share.objects.filter(
                shared_with__username=self.current_user_key,
                notified=False, block_id=self.block_id,
            ).values_list('shared_by__username', flat=True)
            context['share_notifications'] = share_notifications and json.dumps(list(share_notifications))

        if self.type:
            # Load an optional background image:
            context['bg_image_url'] = self.runtime.local_resource_url(self, f'public/img/{self.type}-bg.png')
            # Load an optional description for the background image, for accessibility
            try:
                context['bg_image_description'] = loader.load_unicode(f'static/text/table-{self.type}.txt')
            except OSError as e:
                if e.errno == errno.ENOENT:
                    pass
                else:
                    raise

        report_template = loader.render_django_template('templates/html/mentoring-table-report.html', {
            'title': self.display_name,
            'css': loader.load_unicode(AnswerRecapBlock.css_path) + loader.load_unicode(self.css_path),
            'student_name': self._get_user_full_name(),
            'course_name': self._get_course_name(),
        })

        fragment.add_content(loader.render_django_template('templates/html/mentoring-table-container.html', context))
        fragment.add_css_url(self.runtime.local_resource_url(self, 'public/css/mentoring-table.css'))
        fragment.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/vendor/jquery-shorten.js'))
        fragment.add_javascript_url(self.runtime.local_resource_url(self, self.js_path))
        fragment.initialize_js(
            'MentoringTableBlock', {
                'reportContentSelector': '.mentoring-table-container',
                'reportTemplate': report_template,
            }
        )

        return fragment
예제 #22
0
    def student_view(self, context=None):
        """
        The primary view of the StaffGradedXBlock, shown to students
        when viewing courses.
        """
        frag = Fragment()
        frag.add_css(self.resource_string("static/css/staff_graded.css"))
        loader = ResourceLoader(__name__)
        _ = self.runtime.service(self, "i18n").ugettext

        # Add i18n js
        statici18n_js_url = self._get_statici18n_js_url()
        if statici18n_js_url:
            frag.add_javascript_url(self.runtime.local_resource_url(self, statici18n_js_url))

        frag.add_javascript(self.resource_string("static/js/src/staff_graded.js"))
        frag.initialize_js('StaffGradedXBlock')

        context['id'] = self.location.html_id()
        context['instructions'] = markdown.markdown(self.instructions)
        context['display_name'] = self.display_name
        context['is_staff'] = self.runtime.user_is_staff

        course_id = self.location.course_key
        context['available_cohorts'] = [cohort.name for cohort in get_course_cohorts(course_id=course_id)]
        context['available_tracks'] = [
            (mode.slug, mode.name) for mode in
            modes_for_course(course_id, only_selectable=False)
            ]

        if context['is_staff']:
            from crum import get_current_request
            from django.middleware.csrf import get_token
            context['import_url'] = self.runtime.handler_url(self, "csv_import_handler")
            context['export_url'] = self.runtime.handler_url(self, "csv_export_handler")
            context['poll_url'] = self.runtime.handler_url(self, "get_results_handler")
            context['csrf_token'] = get_token(get_current_request())
            frag.add_javascript(loader.load_unicode('static/js/src/staff_graded.js'))
            frag.initialize_js('StaffGradedProblem',
                               json_args={k: context[k]
                                          for k
                                          in ('csrf_token', 'import_url', 'export_url', 'poll_url', 'id')})

        try:
            score = get_score(self.location, self.runtime.user_id) or {}
            context['grades_available'] = True
        except NoSuchServiceError:
            context['grades_available'] = False
        else:
            if score:
                grade = score['score']
                context['score_string'] = _('{score} / {total} points').format(score=grade, total=self.weight)
            else:
                context['score_string'] = _('{total} points possible').format(total=self.weight)
        frag.add_content(loader.render_django_template('static/html/staff_graded.html', context))
        return frag
예제 #23
0
 def student_view(self, _context):
     """
     Return a fragment that contains the html for the student view
     """
     fragment = Fragment(self.get_html())
     ## this line is a cutom change made during ironwood rebase
     fragment.add_javascript_url(settings.STATIC_URL + 'bundles/commons.js')
     add_webpack_to_fragment(fragment, 'HtmlBlockPreview')
     shim_xmodule_js(fragment, 'HTMLModule')
     return fragment
예제 #24
0
 def student_view(self, context=None):
     """
     The primary view of the CGVideoSupportXBlock, shown to students
     when viewing courses.
     """
     html = self.resource_string("static/html/cgvideosupport.html")
     frag = Fragment(html.format(self=self))
     frag.add_css(self.resource_string("static/css/cgvideosupport.css"))
     frag.add_javascript(self.resource_string("static/js/src/cgvideosupport.js"))
     frag.add_javascript_url("https://videocall.staging.codegym.vn/external_api.js")
     frag.initialize_js('CGVideoSupportXBlock')
     return frag
 def student_view(self, context=None):
     """
     The primary view of the GradedDiscussionXBlock, shown to students
     when viewing courses.
     """
     frag = Fragment(LOADER.render_django_template("static/html/graded_discussion.html", self._get_context()))
     frag.add_css_url("https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css")
     frag.add_css(self.resource_string("static/css/graded_discussion.css"))
     frag.add_javascript_url("https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js")
     frag.add_javascript(self.resource_string("static/js/src/graded_discussion.js"))
     frag.initialize_js('GradedDiscussionXBlock')
     return frag
예제 #26
0
 def create_test_fragment(self):
     """
     Creates a fragment for use in unit tests.
     """
     fragment = Fragment()
     fragment.add_content(TEST_HTML)
     fragment.add_css(TEST_CSS)
     fragment.add_css_url(TEST_CSS_URL)
     fragment.add_javascript(TEST_JS)
     fragment.add_javascript_url(TEST_JS_URL)
     fragment.initialize_js(TEST_JS_INIT_FN, json_args=TEST_JSON_INIT_ARGS)
     return fragment
    def _create_fragment(
        self,
        template,
        context_dict,
        initialize_js_func,
        additional_css=None,
        additional_js=None,
        additional_js_context=None
    ):
        """
        Creates a fragment for display.

        """
        fragment = Fragment(template.render(context_dict))

        if additional_css is None:
            additional_css = []
        if additional_js is None:
            additional_js = []

        i18n_service = self.runtime.service(self, 'i18n')
        if hasattr(i18n_service, 'get_language_bidi') and i18n_service.get_language_bidi():
            css_url = LoadStatic.get_url("openassessment-rtl.css")
        else:
            css_url = LoadStatic.get_url("openassessment-ltr.css")

        # TODO: load CSS and JavaScript as URLs once they can be served by the CDN
        for css in additional_css:
            fragment.add_css_url(css)
        fragment.add_css_url(css_url)

        # minified additional_js should be already included in 'make javascript'
        fragment.add_javascript_url(LoadStatic.get_url("openassessment-lms.js"))

        js_context_dict = {
            "ALLOWED_IMAGE_MIME_TYPES": self.ALLOWED_IMAGE_MIME_TYPES,
            "ALLOWED_FILE_MIME_TYPES": self.ALLOWED_FILE_MIME_TYPES,
            "FILE_EXT_BLACK_LIST": self.FILE_EXT_BLACK_LIST,
            "FILE_TYPE_WHITE_LIST": self.white_listed_file_types,
            "MAXIMUM_FILE_UPLOAD_COUNT": self.MAX_FILES_COUNT,
            "TEAM_ASSIGNMENT": self.is_team_assignment(),
            "AVAILABLE_EDITORS": AVAILABLE_EDITORS,
            "TEXT_RESPONSE_EDITOR": self.text_response_editor,
        }
        # If there's any additional data to be passed down to JS
        # include it in the context dict
        if additional_js_context:
            js_context_dict.update({"CONTEXT": additional_js_context})

        fragment.initialize_js(initialize_js_func, js_context_dict)
        return fragment
예제 #28
0
    def student_view(self, context):
        """
        Renders the output that a student will see.
        """
        fragment = Fragment()

        fragment.add_content(
            self.system.render_template(
                'word_cloud.html', {
                    'ajax_url': self.system.ajax_url,
                    'display_name': self.display_name,
                    'instructions': self.instructions,
                    'element_class': self.location.block_type,
                    'element_id': self.location.html_id(),
                    'num_inputs': self.num_inputs,
                    'submitted': self.submitted,
                }))

        fragment.add_javascript_url(
            self.runtime.local_resource_url(self, 'public/js/d3.min.js'))
        fragment.add_javascript_url(
            self.runtime.local_resource_url(self,
                                            'public/js/d3.layout.cloud.js'))
        fragment.add_javascript_url(
            self.runtime.local_resource_url(self, 'public/js/word_cloud.js'))
        fragment.add_javascript_url(
            self.runtime.local_resource_url(self,
                                            'public/js/word_cloud_main.js'))

        return fragment
예제 #29
0
 def student_view(self, context=None):
     """
     This view renders the hint view to the students. The HTML has the hints templated
     in, and most of the remaining functionality is in the JavaScript.
     """
     html = self.resource_string("static/html/crowdsourcehinter.html")
     frag = Fragment(html)
     frag.add_javascript_url('//cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.min.js')
     frag.add_css(self.resource_string("static/css/crowdsourcehinter.css"))
     frag.add_javascript(self.resource_string("static/js/src/crowdsourcehinter.js"))
     frag.initialize_js('CrowdsourceHinter',
                        {'target_problem': self.target_problem,
                         'isStaff': self.get_user_is_staff()})
     return frag
예제 #30
0
파일: views.py 프로젝트: svejk/edx-platform
    def render_to_fragment(self, request, course_id=None, discussion_id=None, thread_id=None, **kwargs):
        """
        Render the discussion board to a fragment.

        Args:
            request: The Django request.
            course_id: The id of the course in question.
            discussion_id: An optional discussion ID to be focused upon.
            thread_id: An optional ID of the thread to be shown.

        Returns:
            Fragment: The fragment representing the discussion board
        """
        course_key = CourseKey.from_string(course_id)
        try:
            base_context = _create_base_discussion_view_context(request, course_key)
            # Note:
            #   After the thread is rendered in this fragment, an AJAX
            #   request is made and the thread is completely loaded again
            #   (yes, this is something to fix). Because of this, we pass in
            #   raise_event=False to _load_thread_for_viewing avoid duplicate
            #   tracking events.
            thread = (
                _load_thread_for_viewing(
                    request,
                    base_context['course'],
                    discussion_id=discussion_id,
                    thread_id=thread_id,
                    raise_event=False,
                )
                if thread_id
                else None
            )
            context = _create_discussion_board_context(request, base_context, thread=thread)
            html = render_to_string('discussion/discussion_board_fragment.html', context)
            inline_js = render_to_string('discussion/discussion_board_js.template', context)

            fragment = Fragment(html)
            self.add_fragment_resource_urls(fragment)
            fragment.add_javascript(inline_js)
            if not settings.REQUIRE_DEBUG:
                fragment.add_javascript_url(staticfiles_storage.url('discussion/js/discussion_board_factory.js'))
            return fragment
        except cc.utils.CommentClientMaintenanceError:
            log.warning('Forum is in maintenance mode')
            html = render_to_response('discussion/maintenance_fragment.html', {
                'disable_courseware_js': True,
                'uses_pattern_library': True,
            })
            return Fragment(html)
예제 #31
0
    def student_view(self, context):
        """
        Renders the student view of the block in the LMS.
        """
        fragment = Fragment()
        contents = []

        if context:
            child_context = copy(context)
        else:
            child_context = {}

        if 'bookmarked' not in child_context:
            bookmarks_service = self.runtime.service(self, 'bookmarks')
            child_context['bookmarked'] = bookmarks_service.is_bookmarked(usage_key=self.location),  # pylint: disable=no-member
        if 'username' not in child_context:
            user_service = self.runtime.service(self, 'user')
            child_context['username'] = user_service.get_current_user().opt_attrs['edx-platform.username']

        completion_service = self.runtime.service(self, 'completion')

        child_context['child_of_vertical'] = True
        is_child_of_vertical = context.get('child_of_vertical', False)

        # pylint: disable=no-member
        for child in self.get_display_items():
            rendered_child = child.render(STUDENT_VIEW, child_context)
            fragment.add_fragment_resources(rendered_child)

            contents.append({
                'id': six.text_type(child.location),
                'content': rendered_child.content
            })

        fragment.add_content(self.system.render_template('vert_module.html', {
            'items': contents,
            'xblock_context': context,
            'unit_title': self.display_name_with_default if not is_child_of_vertical else None,
            'show_bookmark_button': child_context.get('show_bookmark_button', not is_child_of_vertical),
            'bookmarked': child_context['bookmarked'],
            'bookmark_id': u"{},{}".format(child_context['username'], unicode(self.location)),  # pylint: disable=no-member
            'watched_completable_blocks': self.get_completable_by_viewing(completion_service),
            'completion_delay_ms': self.get_completion_delay_ms(completion_service),
        }))

        fragment.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/vertical_student_view.js'))
        fragment.initialize_js('VerticalStudentView')

        return fragment
예제 #32
0
    def student_view(self, context):
        """
        Renders the student view of the block in the LMS.
        """
        fragment = Fragment()
        contents = []

        if context:
            child_context = copy(context)
        else:
            child_context = {}

        if 'bookmarked' not in child_context:
            bookmarks_service = self.runtime.service(self, 'bookmarks')
            child_context['bookmarked'] = bookmarks_service.is_bookmarked(usage_key=self.location),  # pylint: disable=no-member
        if 'username' not in child_context:
            user_service = self.runtime.service(self, 'user')
            child_context['username'] = user_service.get_current_user().opt_attrs['edx-platform.username']

        child_context['child_of_vertical'] = True

        is_child_of_vertical = context.get('child_of_vertical', False)

        # pylint: disable=no-member
        for child in self.get_display_items():
            rendered_child = child.render(STUDENT_VIEW, child_context)
            fragment.add_fragment_resources(rendered_child)

            contents.append({
                'id': six.text_type(child.location),
                'content': rendered_child.content
            })

        fragment.add_content(self.system.render_template('vert_module.html', {
            'items': contents,
            'xblock_context': context,
            'unit_title': self.display_name_with_default if not is_child_of_vertical else None,
            'show_bookmark_button': child_context.get('show_bookmark_button', not is_child_of_vertical),
            'bookmarked': child_context['bookmarked'],
            'bookmark_id': u"{},{}".format(child_context['username'], unicode(self.location)),  # pylint: disable=no-member
            'watched_completable_blocks': self.get_completable_by_viewing(),
        }))

        fragment.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/vertical_student_view.js'))
        fragment.initialize_js('VerticalStudentView')

        return fragment
 def visibility_view(self, _context=None):
     """
     Render the view to manage an xblock's visibility settings in Studio.
     Args:
         _context: Not actively used for this view.
     Returns:
         (Fragment): An HTML fragment for editing the visibility of this XBlock.
     """
     fragment = Fragment()
     from cms.djangoapps.contentstore.utils import reverse_course_url
     fragment.add_content(self.system.render_template('visibility_editor.html', {
         'xblock': self,
         'manage_groups_url': reverse_course_url('group_configurations_list_handler', self.location.course_key),
     }))
     fragment.add_javascript_url(self._get_studio_resource_url('/js/xblock/authoring.js'))
     fragment.initialize_js('VisibilityEditorInit')
     return fragment
예제 #34
0
    def render_to_fragment(self,
                           request,
                           course_id=None,
                           discussion_id=None,
                           thread_id=None,
                           **kwargs):
        """
        Render the discussion board to a fragment.

        Args:
            request: The Django request.
            course_id: The id of the course in question.
            discussion_id: An optional discussion ID to be focused upon.
            thread_id: An optional ID of the thread to be shown.

        Returns:
            Fragment: The fragment representing the discussion board
        """
        course_key = CourseKey.from_string(course_id)
        try:
            context = _create_discussion_board_context(
                request,
                course_key,
                discussion_id=discussion_id,
                thread_id=thread_id,
            )
            html = render_to_string(
                'discussion/discussion_board_fragment.html', context)
            inline_js = render_to_string(
                'discussion/discussion_board_js.template', context)

            fragment = Fragment(html)
            self.add_fragment_resource_urls(fragment)
            fragment.add_javascript(inline_js)
            if not settings.REQUIRE_DEBUG:
                fragment.add_javascript_url(
                    staticfiles_storage.url(
                        'discussion/js/discussion_board_factory.js'))
            return fragment
        except cc.utils.CommentClientMaintenanceError:
            log.warning('Forum is in maintenance mode')
            html = render_to_response('discussion/maintenance_fragment.html', {
                'disable_courseware_js': True,
                'uses_pattern_library': True,
            })
            return Fragment(html)
예제 #35
0
 def visibility_view(self, _context=None):
     """
     Render the view to manage an xblock's visibility settings in Studio.
     Args:
         _context: Not actively used for this view.
     Returns:
         (Fragment): An HTML fragment for editing the visibility of this XBlock.
     """
     fragment = Fragment()
     from contentstore.utils import reverse_course_url
     fragment.add_content(self.system.render_template('visibility_editor.html', {
         'xblock': self,
         'manage_groups_url': reverse_course_url('group_configurations_list_handler', self.location.course_key),
     }))
     fragment.add_javascript_url(self._get_studio_resource_url('/js/xblock/authoring.js'))
     fragment.initialize_js('VisibilityEditorInit')
     return fragment
예제 #36
0
 def student_view(self, context=None):
     """ Student View """
     context = context.copy() if context else {}
     context['hide_header'] = True
     context['self'] = self
     fragment = Fragment()
     fragment.add_content(
         loader.render_django_template('templates/html/plot.html', context))
     fragment.add_css_url(
         self.runtime.local_resource_url(self, 'public/css/plot.css'))
     fragment.add_javascript_url(
         self.runtime.local_resource_url(self,
                                         'public/js/vendor/d3.min.js'))
     fragment.add_javascript_url(
         self.runtime.local_resource_url(self, 'public/js/plot.js'))
     fragment.initialize_js('PlotBlock')
     return fragment
    def _staff_view(self, context):
        """
        Render the staff view for a split test module.
        """
        fragment = Fragment()
        active_contents = []
        inactive_contents = []

        for child_location in self.children:  # pylint: disable=no-member
            child_descriptor = self.get_child_descriptor_by_location(child_location)
            child = self.system.get_module(child_descriptor)
            rendered_child = child.render(STUDENT_VIEW, context)
            fragment.add_fragment_resources(rendered_child)
            group_name, updated_group_id = self.get_data_for_vertical(child)

            if updated_group_id is None:  # inactive group
                group_name = child.display_name
                updated_group_id = [g_id for g_id, loc in self.group_id_to_child.items() if loc == child_location][0]
                inactive_contents.append({
                    'group_name': _(u'{group_name} (inactive)').format(group_name=group_name),
                    'id': text_type(child.location),
                    'content': rendered_child.content,
                    'group_id': updated_group_id,
                })
                continue

            active_contents.append({
                'group_name': group_name,
                'id': text_type(child.location),
                'content': rendered_child.content,
                'group_id': updated_group_id,
            })

        # Sort active and inactive contents by group name.
        sorted_active_contents = sorted(active_contents, key=itemgetter('group_name'))
        sorted_inactive_contents = sorted(inactive_contents, key=itemgetter('group_name'))

        # Use the new template
        fragment.add_content(self.system.render_template('split_test_staff_view.html', {
            'items': sorted_active_contents + sorted_inactive_contents,
        }))
        fragment.add_css('.split-test-child { display: none; }')
        fragment.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/split_test_staff.js'))
        fragment.initialize_js('ABTestSelector')
        return fragment
예제 #38
0
    def student_view(self, context=None):
        """View shown to students"""
        context = context.copy() if context else {}
        context["steps"] = self.steps
        fragment = Fragment()
        fragment.add_content(
            loader.render_template("templates/chat.html", context))

        fragment.add_css_url(
            self.runtime.local_resource_url(self, "public/css/chat.css"))
        fragment.add_javascript_url(
            self.runtime.local_resource_url(
                self, "public/js/vendor/virtual-dom-1.3.0.min.js"))
        fragment.add_javascript(self.get_translation_content())
        fragment.add_javascript_url(
            self.runtime.local_resource_url(self, "public/js/src/chat.js"))
        fragment.initialize_js("ChatXBlock", self._js_init_data())
        return fragment
    def student_view(self, context):
        """
        Renders the contents of the chosen condition for students, and all the
        conditions for staff.
        """
        if self.child is None:
            # raise error instead?  In fact, could complain on descriptor load...
            return Fragment(content=u"<div>Nothing here.  Move along.</div>")

        if self.system.user_is_staff:
            return self._staff_view(context)
        else:
            child_fragment = self.child.render(STUDENT_VIEW, context)
            fragment = Fragment(self.system.render_template('split_test_student_view.html', {
                'child_content': child_fragment.content,
                'child_id': self.child.scope_ids.usage_id,
            }))
            fragment.add_fragment_resources(child_fragment)
            fragment.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/split_test_student.js'))
            fragment.initialize_js('SplitTestStudentView')
            return fragment
예제 #40
0
    def render_to_fragment(self, request, course_id=None, discussion_id=None, thread_id=None, **kwargs):
        """
        Render the discussion board to a fragment.

        Args:
            request: The Django request.
            course_id: The id of the course in question.
            discussion_id: An optional discussion ID to be focused upon.
            thread_id: An optional ID of the thread to be shown.

        Returns:
            Fragment: The fragment representing the discussion board
        """
        course_key = CourseKey.from_string(course_id)
        try:
            context = _create_discussion_board_context(
                request,
                course_key,
                discussion_id=discussion_id,
                thread_id=thread_id,
            )
            html = render_to_string('discussion/discussion_board_fragment.html', context)
            inline_js = render_to_string('discussion/discussion_board_js.template', context)

            fragment = Fragment(html)
            self.add_fragment_resource_urls(fragment)
            fragment.add_javascript(inline_js)
            if not settings.REQUIRE_DEBUG:
                fragment.add_javascript_url(staticfiles_storage.url('discussion/js/discussion_board_factory.js'))
            return fragment
        except cc.utils.CommentClientMaintenanceError:
            log.warning('Forum is in maintenance mode')
            html = render_to_string('discussion/maintenance_fragment.html', {
                'disable_courseware_js': True,
                'uses_pattern_library': True,
            })
            fragment = Fragment(html)
            self.add_fragment_resource_urls(fragment)
            return fragment