def _list_question_groups( handler, all_questions, all_question_groups, locations_map): """Prepare a list of question groups.""" if not handler.app_context.is_editable_fs(): return safe_dom.NodeList() question_group_infos = [] quid_to_question = {long(qu.id): qu for qu in all_questions} for question_group in all_question_groups: url = 'dashboard?action=edit_question_group&key=%s' % ( question_group.id) question_descriptions = sorted([ quid_to_question[long(quid)].description for quid in question_group.question_ids]) locations = locations_map.get(question_group.id, {}) question_group_infos.append(dict( description=question_group.description, id=question_group.id, locations=locations, last_modified=question_group.last_modified, question_descriptions=question_descriptions, url=url)) return safe_dom.Template( jinja_utils.get_template('question_group_list.html', [TEMPLATE_DIR]), question_groups=question_group_infos)
def render(self, node, context): """Renders the submit button.""" xsrf_token = XsrfTokenManager.create_xsrf_token( QUESTIONNAIRE_XSRF_TOKEN_NAME) form_id = node.attrib.get('form-id') button_label = node.attrib.get('button-label') disabled = (node.attrib.get('disabled') == 'true') post_message = node.text user = context.handler.get_user() registered = False if user and models.Student.get_enrolled_student_by_user(user): registered = True template_vals = { 'xsrf_token': xsrf_token, 'form_id': form_id, 'button_label': button_label, 'disabled': disabled, 'registered': registered, 'post_message': post_message, } template = jinja_utils.get_template( 'questionnaire.html', [TEMPLATES_DIR]) button = template.render(template_vals) return tags.html_string_to_element_tree(button)
def get(self): """Handles GET requests.""" student = self.personalize_page_and_get_enrolled( supports_transient_student=True) if not student: return u = self.request.get('unit') target = None title = None unit = None if u: unit = self.get_course().find_unit_by_id(u) if unit and unit.type == 'O' : target = unit.href title = unit.title self.template_value['unit'] = unit self.template_value['unit_id'] = unit.parent_unit if not unit: target = self.request.get('target') if not target: self.redirect('/') return self.template_value['target'] = target if title: self.template_value['title'] = title self.template_value['navbar'] = {} self.template_value['base'] = self.get_template('base_course.html') template = jinja_utils.get_template( 'link.html', [os.path.dirname(__file__)]) self.render(template)
def render(self, node, handler): """Renders the custom tag.""" student = handler.personalize_page_and_get_enrolled( supports_transient_student=True) template = jinja_utils.get_template('templates/form.html', os.path.dirname(__file__)) already_submitted = False if not isinstance(student, models.TransientStudent): already_submitted = bool( db.get( student_work.Submission.get_key(handler.unit_id, student.get_key()))) handler.template_value['action'] = self._get_action( handler.app_context.get_slug()) handler.template_value['already_submitted'] = already_submitted handler.template_value['display_length'] = node.attrib.get( 'display_length') handler.template_value['form_xsrf_token'] = ( utils.XsrfTokenManager.create_xsrf_token(_XSRF_TOKEN_NAME)) handler.template_value['unit_id'] = handler.unit_id return tags.html_string_to_element_tree( jinja2.utils.Markup(template.render(handler.template_value)))
def get_template(self, template_name, dirs): """Sets up an environment and Gets jinja template.""" dashboard_template_dir = os.path.join(appengine_config.BUNDLE_ROOT, 'modules', 'dashboard') return jinja_utils.get_template(template_name, dirs + [dashboard_template_dir], handler=self)
def get(self): """Handles GET requests.""" if not course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value: self.error(404) return user = self.initialize_page_and_get_user() if not user: self.redirect('/explorer') return courses = self.get_public_courses() self.template_values['student'] = ( StudentProfileDAO.get_profile_by_user_id(user.user_id())) self.template_values['navbar'] = {'profile': True} self.template_values['courses'] = self.get_enrolled_courses(courses) self.template_values['student_edit_xsrf_token'] = ( XsrfTokenManager.create_xsrf_token( STUDENT_RENAME_GLOBAL_XSRF_TOKEN_ID)) self.template_values['html_hooks'] = NullHtmlHooks() self.template_values['student_preferences'] = {} template = jinja_utils.get_template( '/modules/course_explorer/views/profile.html', DIR) self.response.write(template.render(self.template_values))
def render(self, node, handler): instanceid = node.attrib.get('instanceid') template_values = { 'RESOURCES_PATH': RESOURCES_PATH, 'exploration_id': node.attrib.get('exploration_id'), 'instanceid': instanceid, 'src': node.attrib.get('src'), } cpt_progress = None if (hasattr(handler, 'student') and not handler.student.is_transient and not handler.lesson_is_scored): cpt_progress = handler.get_course().get_progress_tracker( ).get_component_progress(handler.student, handler.unit_id, handler.lesson_id, instanceid) template_values['progress'] = cpt_progress locale = handler.app_context.get_environ()['course']['locale'] template = jinja_utils.get_template('templates/oppia_template.html', [os.path.dirname(__file__)], locale=locale) html_string = jinja2.utils.Markup(template.render(template_values)) return tags.html_string_to_element_tree(html_string)
def get(self): if not courses.COURSES_CAN_USE_GOOGLE_APIS.value: self.error(404) return resource_id = self.request.get('resource_id') type_id = self.request.get('type_id') if not (resource_id and type_id): self._handle_error(400, 'Bad request') return matches = models.ContentChunkDAO.get_by_uid( models.ContentChunkDAO.make_uid(type_id, resource_id)) if not matches: self._handle_error(404, 'Content chunk not found') return # There is a data race in the DAO -- it's possible to create two entries # at the same time with the same UID. If that happened, use the first # one saved. chunk = matches[0] template = jinja_utils.get_template('drive_item.html', [_TEMPLATES_ABSPATH]) self.response.out.write(template.render({'contents': chunk.contents}))
def _generate_html_from_template(cls, template_name, template_value): """Generates marked-up HTML from template.""" template = jinja_utils.get_template( template_name, [os.path.join(appengine_config.BUNDLE_ROOT, 'modules', 'search', 'results_templates')]) return jinja2.Markup(template.render(template_value))
def get_evaluate_offline(cls, handler): assessment_id = handler.request.get('assessment_id') if not assessment_id: handler.error(404) handler.redirect('/course_staff') return course = handler.get_course() unit = course.find_unit_by_id(assessment_id) if not unit: handler.error(404) handler.redirect('/course_staff') handler.template_value['form_uri'] = 'course_staff' handler.template_value['form_action'] = 'score_offline' handler.template_value['score_offline_xsrf_token'] = ( handler.create_xsrf_token('score_offline')) handler.template_value['unit'] = unit handler.template_value[ 'CUSTOM_UNITS'] = course_staff.CourseStaff.CUSTOM_UNITS template_file = 'templates/course_staff/evaluate_offline.html' template = jinja_utils.get_template(template_file, [os.path.dirname(__file__)]) handler.render(template)
def guide_get(self, config): student, can_display, displayability = ( can_display_guide_to_current_user(self.get_course(), config)) if not can_display: self.error( 404, 'Negative displayability: %s' % str(displayability)) return unit_id = self.request.get('unit_id') if not unit_id: self.error(404, 'Bad unit_id') return view = unit_outline.StudentCourseView( self.get_course(), student=student) unit = self.get_course().find_unit_by_id(unit_id) if not unit in view.get_units(): self.error(404, 'Unit not visible') return self.prepare(config, view, student, unit, view.get_lessons(unit.unit_id), self.template_value) template = jinja_utils.get_template( 'steps.html', TEMPLATE_DIRS, handler=self) self.response.write(template.render(self.template_value))
def get(self): if not courses.COURSES_CAN_USE_GOOGLE_APIS.value: self.error(404) return resource_id = self.request.get('resource_id') type_id = self.request.get('type_id') if not (resource_id and type_id): self._handle_error(400, 'Bad request') return matches = models.ContentChunkDAO.get_by_uid( models.ContentChunkDAO.make_uid(type_id, resource_id)) if not matches: self._handle_error(404, 'Content chunk not found') return # There is a data race in the DAO -- it's possible to create two entries # at the same time with the same UID. If that happened, use the first # one saved. chunk = matches[0] template = jinja_utils.get_template( 'drive_item.html', [_TEMPLATES_ABSPATH]) self.response.out.write(template.render({'contents': chunk.contents}))
def _write_result(self, service_name, result): template = jinja_utils.get_template('result.html', [_TEMPLATES_DIR]) self.response.out.write( template.render({ 'service_name': service_name, 'result': result, }))
def render(self, node, handler): """Renders the custom tag.""" student = handler.personalize_page_and_get_enrolled( supports_transient_student=True) template = jinja_utils.get_template( 'templates/form.html', os.path.dirname(__file__), locale=handler.app_context.get_environ()['course']['locale'], ) already_submitted = False if not isinstance(student, models.TransientStudent): already_submitted = bool( db.get(student_work.Submission.get_key( handler.unit_id, student.get_key()))) handler.template_value['action'] = self._get_action( handler.app_context.get_slug()) handler.template_value['already_submitted'] = already_submitted handler.template_value['display_length'] = node.attrib.get( 'display_length') handler.template_value['form_xsrf_token'] = ( utils.XsrfTokenManager.create_xsrf_token( _XSRF_TOKEN_NAME)) handler.template_value['unit_id'] = handler.unit_id return tags.html_string_to_element_tree( jinja2.utils.Markup(template.render(handler.template_value)) )
def render(self, node, handler): """Renders the custom tag.""" student = handler.personalize_page_and_get_enrolled( supports_transient_student=True) enabled = ( not isinstance(student, models.TransientStudent) and hasattr(handler, 'unit_id')) template_value = {} template_value['enabled'] = enabled template = jinja_utils.get_template( 'templates/form.html', os.path.dirname(__file__)) already_submitted = False if enabled: instance_id = node.attrib.get('instanceid') already_submitted = bool( student_work.Submission.get( handler.unit_id, student.get_key(), instance_id=instance_id)) template_value['unit_id'] = handler.unit_id template_value['instance_id'] = instance_id template_value['action'] = self._get_action( handler.app_context.get_slug()) template_value['already_submitted'] = already_submitted template_value['display_length'] = node.attrib.get( 'display_length') template_value['form_xsrf_token'] = ( utils.XsrfTokenManager.create_xsrf_token(_XSRF_TOKEN_NAME)) return tags.html_string_to_element_tree( jinja2.utils.Markup(template.render(template_value)) )
def get(self): self.response.write(jinja_utils.get_template( 'explorer.html', [constants.TEMPLATE_DIR], handler=self).render({ 'institution_name': get_institution_name(), 'use_flattened_html_imports': ( appengine_config.USE_FLATTENED_HTML_IMPORTS), }))
def render(self, node, handler): instanceid = node.attrib.get('instanceid') template_values = { 'RESOURCES_PATH': RESOURCES_PATH, 'exploration_id': node.attrib.get('exploration_id'), 'instanceid': instanceid, 'src': node.attrib.get('src'), } cpt_progress = None if (hasattr(handler, 'student') and not handler.student.is_transient and not handler.lesson_is_scored): cpt_progress = handler.get_course().get_progress_tracker( ).get_component_progress( handler.student, handler.unit_id, handler.lesson_id, instanceid) template_values['progress'] = cpt_progress locale = handler.app_context.get_environ()['course']['locale'] template = jinja_utils.get_template( 'templates/oppia_template.html', [os.path.dirname(__file__)], locale=locale) html_string = jinja2.utils.Markup(template.render(template_values)) return tags.html_string_to_element_tree(html_string)
def _handle_error(self, code, message): template = jinja_utils.get_template( 'drive_error.html', [_TEMPLATES_ABSPATH]) self.error(code) self.response.out.write(template.render({ 'code': code, 'message': message, }))
def get(self): template = jinja_utils.get_template('index.html', [_TEMPLATES_PATH]) self.response.write(template.render({ 'course': self.get_course(), 'login_url': users.create_login_url(self.request.path), 'logout_url': users.create_logout_url(self.request.path), 'user': users.get_current_user(), }))
def render_question( quid, instanceid, locale, embedded=False, weight=None, progress=None): """Generates the HTML for a question. Args: quid: String. The question id. instanceid: String. The unique reference id for the question instance (different instances of the same question in a page will have different instanceids). locale: String. The locale for the Jinja environment that is used to generate the question HTML. embedded: Boolean. Whether this question is embedded within a container object. weight: float. The weight to be used when grading the question in a scored lesson. progress: None, 0 or 1. If None, no progress marker should be shown. If 0, a 'not-started' progress marker should be shown. If 1, a 'complete' progress marker should be shown. Returns: a Jinja markup string that represents the HTML for the question. """ question_dto = m_models.QuestionDAO.load(quid) if not question_dto: return '[Question deleted]' template_values = question_dto.dict template_values['embedded'] = embedded template_values['instanceid'] = instanceid template_values['resources_path'] = RESOURCES_PATH if progress is not None: template_values['progress'] = progress template_file = None js_data = {} if question_dto.type == question_dto.MULTIPLE_CHOICE: template_file = 'templates/mc_question.html' multi = template_values['multiple_selections'] template_values['button_type'] = 'checkbox' if multi else 'radio' choices = [{ 'score': choice['score'], 'feedback': choice.get('feedback') } for choice in template_values['choices']] js_data['choices'] = choices elif question_dto.type == question_dto.SHORT_ANSWER: template_file = 'templates/sa_question.html' js_data['graders'] = template_values['graders'] js_data['hint'] = template_values.get('hint') js_data['defaultFeedback'] = template_values.get('defaultFeedback') if not embedded: js_data['weight'] = weight template_values['js_data'] = transforms.dumps(js_data) template = jinja_utils.get_template( template_file, [os.path.dirname(__file__)], locale=locale) return jinja2.utils.Markup(template.render(template_values))
def _real_get(self): # Add content to templates/branding.html to customize the lefthand side # of the accountchooser.com UX. This HTML is scrubbed by # accountchooser.com before render; see # https://developers.google.com/identity/toolkit/web/setup-frontend for # details. template = jinja_utils.get_template( _BRANDING_TEMPLATE_PATH, [_TEMPLATES_DIR]) self.response.out.write(template.render({}))
def get(self): self.response.write(jinja_utils.get_template( 'guide.html', [constants.TEMPLATE_DIR], handler=self).render({ 'event_xsrf_token': get_event_xsrf_token(), 'can_record_student_events': ( get_can_record_student_events(self)), 'use_flattened_html_imports': ( appengine_config.USE_FLATTENED_HTML_IMPORTS), }))
def get(self): self.response.write( jinja_utils.get_template( 'explorer.html', [constants.TEMPLATE_DIR], handler=self).render({ 'institution_name': get_institution_name(), 'use_flattened_html_imports': (appengine_config.USE_FLATTENED_HTML_IMPORTS), }))
def get(self): """Handles GET requests.""" self.initialize_page_and_get_user() courses = self.get_public_courses() self.template_values['courses'] = ( [self.get_course_info(course) for course in courses]) self.template_values['navbar'] = {'course_explorer': True} template = jinja_utils.get_template( '/modules/course_explorer/views/course_explorer.html', DIR, LOCALE) self.response.write(template.render(self.template_values))
def get(self): self.response.write( jinja_utils.get_template( 'guide.html', [constants.TEMPLATE_DIR], handler=self).render({ 'event_xsrf_token': get_event_xsrf_token(), 'can_record_student_events': (get_can_record_student_events(self)), 'use_flattened_html_imports': (appengine_config.USE_FLATTENED_HTML_IMPORTS), }))
def get(self): template_data = {} all_courses = self.get_courses() if not all_courses: self.error(404, 'No courses to display') return template_data['courses'] = sorted(all_courses, key=lambda x: x[1]) template = jinja_utils.get_template('guides.html', TEMPLATE_DIRS) self.response.write(template.render(template_data))
def _handle_error(self, code, private_message, public_message=None): if public_message is None: public_message = private_message template = jinja_utils.get_template('error.html', [_TEMPLATES_DIR]) _LOG.error(private_message) self.error(code) self.response.out.write( template.render({ 'status_message': self.response.status_message, 'details': public_message }))
def get_list_subjective(cls, handler): user = handler.current_user evaluator = handler.evaluator assignment_name = handler.request.get('name') course = handler.get_course() unit = course.find_unit_by_id(assignment_name) if not unit: handler.error(404) handler.redirect('/course') return show_evaluated = handler.request.get('show_evaluated') override = evaluator.can_override and handler.request.get('override') if evaluate.EvaluationHandler.can_evaluate(unit): handler.template_value['can_evaluate'] = True handler.template_value['show_evaluated'] = show_evaluated handler.template_value[ 'show_override'] = evaluator.can_override and not override if override: override_work = staff.ManualEvaluationStep.all().filter( staff.ManualEvaluationStep.unit_id.name, assignment_name).filter('removed =', False).fetch(None) handler.template_value['override_work'] = override_work elif show_evaluated: completed_work = staff.ManualEvaluationStep.all().filter( staff.ManualEvaluationStep.evaluator.name, user.user_id()).filter( staff.ManualEvaluationStep.state.name, staff.REVIEW_STATE_COMPLETED).filter( staff.ManualEvaluationStep.unit_id.name, assignment_name).filter('removed =', False).fetch(None) handler.template_value['completed_work'] = completed_work else: pending_work = staff.ManualEvaluationStep.all().filter( staff.ManualEvaluationStep.evaluator.name, user.user_id()).filter( "%s != " % staff.ManualEvaluationStep.state.name, staff.REVIEW_STATE_COMPLETED).filter( staff.ManualEvaluationStep.unit_id.name, assignment_name).filter('removed =', False).fetch(None) handler.template_value['pending_work'] = pending_work else: handler.template_value['can_evaluate'] = False handler.template_value['unit'] = unit handler.template_value['unit_id'] = unit.unit_id template_file = 'templates/course_staff/evaluations.html' template = jinja_utils.get_template(template_file, [os.path.dirname(__file__)]) handler.render(template)
def get(self): """Handles GET request.""" self.initialize_page_and_get_user() courses = self.get_public_courses() enrolled_courses = self.get_enrolled_courses(courses) self.template_values['courses'] = enrolled_courses self.template_values['navbar'] = {'mycourses': True} self.template_values['can_enroll_more_courses'] = ( len(courses) - len(enrolled_courses) > 0) template = jinja_utils.get_template( '/modules/course_explorer/views/course_explorer.html', DIR, LOCALE) self.response.write(template.render(self.template_values))
def _make_welcome_form_content(): """Add content to welcome page to get user's consent for stat collection.""" if messaging.is_disabled(): return None checked = config.REPORT_ALLOWED.value or not config.is_consent_set() return jinja2.Markup( jinja_utils.get_template( 'course_creation.html', [constants.TEMPLATES_DIR]).render( name=USAGE_REPORTING_CONSENT_CHECKBOX_NAME, value=USAGE_REPORTING_CONSENT_CHECKBOX_VALUE, checked=checked))
def _list_labels(handler, items, name, all_paths): """Prepare a list of labels for use on the Assets page.""" if not handler.app_context.is_editable_fs(): return safe_dom.NodeList() labels = sorted( models.LabelDAO.get_all_of_type(models.LabelDTO.LABEL_TYPE_GENERAL), key=lambda label: label.title) items.append(safe_dom.Template( jinja_utils.get_template('label_list.html', [TEMPLATE_DIR]), add_text='Add Label', add_action='add_label', edit_action='edit_label', items=labels))
def post_score_offline(cls, handler): user = handler.current_user evaluator = handler.evaluator errors = list() if not evaluator.can_grade: handler.error(404) errors.append('Failed') return assessment_id = handler.request.get('assessment_id') if not assessment_id: handler.error(404) errors.append('Failed') return course = handler.get_course() unit = course.find_unit_by_id(assessment_id) if not unit: handler.error(404) errors.append('Failed') return csv_text = handler.request.get('scores_csv').strip() if not csv_text: handler.error(400) errors.append('Failed') return if not errors: reader = csv.reader(StringIO.StringIO(csv_text)) # Filter out empty rows reader = [r for r in reader if ''.join(r).strip()] assignment.OfflineAssignmentHandler.bulk_score_by_unit( course, unit, reader, errors) handler.template_value['errors'] = errors handler.template_value['unit'] = unit handler.template_value[ 'CUSTOM_UNITS'] = course_staff.CourseStaff.CUSTOM_UNITS template_file = 'templates/course_staff/evaluation_result_offline.html' template = jinja_utils.get_template(template_file, [ os.path.join(os.getcwd(), 'modules/offline_assignments/templates'), os.path.dirname(__file__) ]) handler.render(template)
def get(self): runtime_config = Runtime.get_current_runtime_config() try: runtime_config.validate() except RuntimeError as e: _LOG.error(e.message) self.error(500) return template = jinja_utils.get_template( _SIGN_OUT_TEMPLATE_PATH, [_TEMPLATES_DIR]) self.response.out.write(template.render({ _BROWSER_API_KEY_NAME: runtime_config.browser_api_key, _DEST_URL_NAME: _DEST_URL_NAME, }))
def get(self): """Handles GET requests.""" user = self.initialize_page_and_get_user() courses = self.get_public_courses() self.template_values['student'] = ( StudentProfileDAO.get_profile_by_user_id(user.user_id())) self.template_values['navbar'] = {'profile': True} self.template_values['courses'] = self.get_enrolled_courses(courses) self.template_values['student_edit_xsrf_token'] = ( XsrfTokenManager.create_xsrf_token( STUDENT_RENAME_GLOBAL_XSRF_TOKEN_ID)) template = jinja_utils.get_template( '/modules/course_explorer/views/profile.html', DIR, LOCALE) self.response.write(template.render(self.template_values))
def get(self): """Handles GET requests.""" if not course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value: self.error(404) return self.initialize_page_and_get_user() courses = self.get_public_courses() self.template_values['courses'] = ( [self.get_course_info(course) for course in courses]) self.template_values['navbar'] = {'course_explorer': True} self.template_values['html_hooks'] = NullHtmlHooks() self.template_values['student_preferences'] = {} template = jinja_utils.get_template( '/modules/course_explorer/views/course_explorer.html', DIR) self.response.write(template.render(self.template_values))
def get(self): runtime = _get_runtime(self.app_context) name = self._get_request_arg(self.request, 'name') resource_link_id = self._get_request_arg(self.request, fields.RESOURCE_LINK_ID) return_url = self._get_request_arg( self.request, fields.LAUNCH_PRESENTATION_RETURN_URL) tool_config = runtime.get_tool_config(name) if not (name and tool_config and resource_link_id and return_url): _LOG.error( 'Unable to attempt LTI launch; invalid parameters: ' 'name: "%(name)s", config: "%(config)s", ' 'resource_link_id: "%(resource_link_id)s", ' 'launch_presentation_return_url: ' '"%(launch_presentation_return_url)s"', { 'name': name, 'config': tool_config, fields.LAUNCH_PRESENTATION_RETURN_URL: return_url, fields.RESOURCE_LINK_ID: resource_link_id }) self.error(400) return template = jinja_utils.get_template('launch.html', [_TEMPLATES_DIR]) extra_fields = self.request.get('extra_fields') if extra_fields: # Treating as module-protected. pylint: disable=protected-access extra_fields = fields._Serializer.load(extra_fields) # We use a *very* minimal set of common args. Other static values can be # passed on an as-needed basis via the tag UI. If you need dynamic # values, you can override _get_custom_unsigned_launch_parameters below. unsigned_parameters = self._get_unsigned_launch_parameters( extra_fields, name, return_url, resource_link_id, tool_config.url, runtime.get_user_id()) signed_parameters = self._get_signed_launch_parameters( tool_config.key, str(tool_config.secret), unsigned_parameters, tool_config.url) self.response.out.write( template.render({ 'signed_parameters': signed_parameters, 'tool_url': tool_config.url, }))
def _list_and_format_file_list( handler, title, subfolder, tab_name, links=False, upload=False, prefix=None, caption_if_empty='< none >', edit_url_template=None, merge_local_files=False, all_paths=None): """Walks files in folders and renders their names in a section.""" assets = [] can_upload = upload and handler.app_context.is_editable_fs() upload_url = 'dashboard?{}'.format(urllib.urlencode({ 'action': 'manage_asset', 'from_action': handler.request.get('action'), 'type': tab_name, 'key': subfolder})) # keep a list of files without merging unmerged_files = {} if merge_local_files: unmerged_files = dashboard_utils.list_files( handler.app_context, subfolder, all_paths=all_paths, merge_local_files=False) for filename in dashboard_utils.list_files( handler.app_context, subfolder, all_paths=all_paths, merge_local_files=merge_local_files): if prefix and not filename.startswith(prefix): continue overridden = (filename in unmerged_files) or (not merge_local_files) if edit_url_template and handler.app_context.fs.impl.is_read_write(): edit_url = edit_url_template % ( tab_name, urllib.quote(filename), handler.request.get('action')) else: edit_url = None assets.append(Asset(filename, overridden, edit_url)) overridden_assets = [asset for asset in assets if asset.overridden] inherited_assets = [asset for asset in assets if not asset.overridden] return safe_dom.Template( jinja_utils.get_template('asset_list.html', [TEMPLATE_DIR]), inherited_assets=inherited_assets, overridden_assets=overridden_assets, can_upload=can_upload, caption_if_empty=caption_if_empty, upload_url=upload_url, links=links)
def get(self): """Handles GET requests.""" if not course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value: self.error(404) return self.initialize_page_and_get_user() courses = self.get_public_courses() self.template_values['courses'] = ([ self.get_course_info(course) for course in courses ]) self.template_values['navbar'] = {'course_explorer': True} self.template_values['html_hooks'] = NullHtmlHooks() self.template_values['student_preferences'] = {} template = jinja_utils.get_template('course_explorer.html', TEMPLATE_DIRS) self.response.write(template.render(self.template_values))
def get(self): resource_id = self.request.get('resource_id') type_id = self.request.get('type_id') if not (resource_id and type_id): self._handle_error(400, 'Bad request') return chunk = models.ContentChunkDAO.get_one_by_uid( models.ContentChunkDAO.make_uid(type_id, resource_id)) if chunk is None: self._handle_error(404, 'Content chunk not found') return template = jinja_utils.get_template( 'drive_item.html', [_TEMPLATES_ABSPATH]) self.response.out.write(template.render({'contents': chunk.contents}))
def do_jinja(self, config, relname=None, from_string=None): assert relname or from_string template_dirs = [ os.path.join( appengine_config.BUNDLE_ROOT, 'modules', 'webserv', WEBSERV_DOC_ROOTS_DIR_NAME, config.get(WEBSERV_DOC_ROOT)), os.path.join( appengine_config.BUNDLE_ROOT, 'views')] if from_string: template = jinja_utils.create_and_configure_jinja_environment( template_dirs, handler=self).from_string(from_string) else: template = jinja_utils.get_template( relname, template_dirs, handler=self) self.response.headers['Content-Type'] = 'text/html' self.template_value['gcb_webserv_metadata'] = self.get_metadata() self.response.write(template.render(self.template_value))
def get(self): runtime_config = Runtime.get_current_runtime_config() try: runtime_config.validate() except RuntimeError as e: _LOG.error(e.message) self.error(500) return template = jinja_utils.get_template( _WIDGET_TEMPLATE_PATH, [_TEMPLATES_DIR]) self.response.out.write(template.render({ _BRANDING_URL_NAME: self._get_branding_url(), _BROWSER_API_KEY_NAME: runtime_config.browser_api_key, _EMAIL_URL_NAME: _EMAIL_URL, _FAVICON_URL_NAME: self._get_favicon_url(), _SIGN_IN_URL_NAME: _SIGN_IN_URL, _TITLE_NAME: runtime_config.title, }))
def render(self, node, handler): """Renders a question.""" locale = handler.app_context.get_environ()['course']['locale'] qgid = node.attrib.get('qgid') group_instanceid = node.attrib.get('instanceid') question_group_dto = m_models.QuestionGroupDAO.load(qgid) if not question_group_dto: return tags.html_string_to_element_tree('[Deleted question group]') template_values = question_group_dto.dict template_values['embedded'] = False template_values['instanceid'] = group_instanceid template_values['resources_path'] = RESOURCES_PATH if (hasattr(handler, 'student') and not handler.student.is_transient and not handler.lesson_is_scored): progress = handler.get_course().get_progress_tracker( ).get_component_progress( handler.student, handler.unit_id, handler.lesson_id, group_instanceid) template_values['progress'] = progress template_values['question_html_array'] = [] js_data = {} for ind, item in enumerate(question_group_dto.dict['items']): quid = item['question'] question_instanceid = '%s.%s.%s' % (group_instanceid, ind, quid) template_values['question_html_array'].append(render_question( quid, question_instanceid, locale, weight=item['weight'], embedded=True )) js_data[question_instanceid] = item template_values['js_data'] = transforms.dumps(js_data) template_file = 'templates/question_group.html' template = jinja_utils.get_template( template_file, [os.path.dirname(__file__)], locale=locale) html_string = template.render(template_values) return tags.html_string_to_element_tree(html_string)
def get(self): """Handles GET request.""" if not course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value: self.error(404) return self.initialize_page_and_get_user() courses = self.get_public_courses() enrolled_courses = self.get_enrolled_courses(courses) self.template_values['courses'] = enrolled_courses self.template_values['navbar'] = {'mycourses': True} self.template_values['can_enroll_more_courses'] = ( len(courses) - len(enrolled_courses) > 0) self.template_values['html_hooks'] = NullHtmlHooks() self.template_values['student_preferences'] = {} template = jinja_utils.get_template( '/modules/course_explorer/views/course_explorer.html', DIR) self.response.write(template.render(self.template_values))
def render(self, node, handler): """Renders a question.""" locale = handler.app_context.get_environ()["course"]["locale"] qgid = node.attrib.get("qgid") group_instanceid = node.attrib.get("instanceid") question_group_dto = m_models.QuestionGroupDAO.load(qgid) if not question_group_dto: return tags.html_string_to_element_tree("[Deleted question group]") template_values = question_group_dto.dict template_values["embedded"] = False template_values["instanceid"] = group_instanceid template_values["resources_path"] = RESOURCES_PATH if hasattr(handler, "student") and not handler.student.is_transient and not handler.lesson_is_scored: progress = ( handler.get_course() .get_progress_tracker() .get_component_progress(handler.student, handler.unit_id, handler.lesson_id, group_instanceid) ) template_values["progress"] = progress template_values["question_html_array"] = [] js_data = {} for ind, item in enumerate(question_group_dto.dict["items"]): quid = item["question"] question_instanceid = "%s.%s.%s" % (group_instanceid, ind, quid) template_values["question_html_array"].append( render_question(quid, question_instanceid, locale, weight=item["weight"], embedded=True) ) js_data[question_instanceid] = item template_values["js_data"] = transforms.dumps(js_data) template_file = "templates/question_group.html" template = jinja_utils.get_template(template_file, [os.path.dirname(__file__)], locale=locale) html_string = template.render(template_values) return tags.html_string_to_element_tree(html_string)
def _write_result(self, service_name, result): template = jinja_utils.get_template("result.html", [_TEMPLATES_DIR]) self.response.out.write(template.render({"service_name": service_name, "result": result}))