def test_rendered_components_which_are_bundled_have_access_to_their_bundle(self):
        bundled_component = render_component(Components.HELLO_WORLD_JS)
        self.assertRaises(ComponentWasNotBundled, bundled_component.get_bundle)

        bundled_component = render_component(Components.HELLO_WORLD_JS, bundle=True)
        self.assertIsInstance(bundled_component.get_bundle(), WebpackBundle)

        translated_component = render_component(Components.HELLO_WORLD_JS, translate=True)
        self.assertIsInstance(translated_component.get_bundle(), WebpackBundle)

        translated_component = render_component(Components.HELLO_WORLD_JS, bundle=True, translate=True)
        self.assertIsInstance(translated_component.get_bundle(), WebpackBundle)
    def test_can_pass_additional_request_headers(self, requests_post_mock):
        mock_json = {
            'markup': '<div>Hello</div>',
        }
        mock_url = 'http://localhost/render'

        response_mock = mock.Mock()
        response_mock.status_code = 200
        response_mock.text = json.dumps(mock_json)
        response_mock.json = mock.Mock(return_value=mock_json)
        requests_post_mock.return_value = response_mock

        mock_settings = Conf()
        mock_settings.configure(RENDER_URL=mock_url)
        with mock.patch('react.conf.settings', mock_settings):
            component = render_component(
                path=Components.HELLO_WORLD_JSX,
                props={'name': 'world!'},
                request_headers={
                    'Accept-language': 'fr-FR,en-US,en',
                },
            )

        requests_post_mock.assert_called_with(
            mock_url,
            data=mock.ANY,
            params=mock.ANY,
            headers={
                'content-type': 'application/json',
                'Accept-language': 'fr-FR,en-US,en',
            },
        )
def render_application(id, step=None, substep=None):
    application = data_api_client.get_application(id)
    if not can_user_view_application(application):
        abort(403, 'Not authorised to access application')
    if is_application_submitted(application) and not current_user.has_role('admin'):
        return redirect(url_for('.submit_application', id=id))

    props = dict(application)
    props['basename'] = url_for('.render_application', id=id, step=None)
    props['form_options'] = {
        'action': url_for('.render_application', id=id, step=step),
        'submit_url': url_for('.submit_application', id=id),
        'document_url': url_for('.upload_single_file', id=id, slug=''),
        'authorise_url': url_for('.authorise_application', id=id),
        'user_name': current_user.name,
        'user_email': current_user.email_address
    }

    # Add service pricing
    if 'services' in application['application']:
        props['application']['domains'] = {'prices': {'maximum': {}}}
        for domain_name in application['application']['services'].keys():
            props['application']['domains']['prices']['maximum'][domain_name] = (
                application['domains']['prices']['maximum'][domain_name]
            )

    widget = application['application'].get('type') == 'edit' and 'ProfileEdit' or 'ApplicantSignup'
    rendered_component = render_component('bundles/SellerRegistration/{}Widget.js'.format(widget), props)

    return render_template(
        '_react.html',
        component=rendered_component
    )
def index():
    component = render_component(os.path.join(os.getcwd(), 'static',
                                              'TodoList.jsx'),
                                 props={'todos': TODOS},
                                 to_static_markup=False)

    return render_template('index.html', component=component)
def render_application(id, step=None, substep=None):
    application = data_api_client.get_application(id)
    if not can_user_view_application(application):
        abort(403, 'Not authorised to access application')
    if is_application_submitted(
            application) and not current_user.has_role('admin'):
        return redirect(url_for('.submit_application', id=id))

    props = dict(application)
    props['basename'] = url_for('.render_application', id=id, step=None)
    props['form_options'] = {
        'action': url_for('.render_application', id=id, step=step),
        'submit_url': url_for('.submit_application', id=id),
        'document_url': url_for('.upload_single_file', id=id, slug=''),
        'authorise_url': url_for('.authorise_application', id=id),
        'user_name': current_user.name,
        'user_email': current_user.email_address
    }

    # Add service pricing
    if 'services' in application['application']:
        props['application']['domains'] = {'prices': {'maximum': {}}}
        for domain_name in application['application']['services'].keys():
            props['application']['domains']['prices']['maximum'][
                domain_name] = (
                    application['domains']['prices']['maximum'][domain_name])

    widget = application['application'].get(
        'type') == 'edit' and 'ProfileEdit' or 'ApplicantSignup'
    rendered_component = render_component(
        'bundles/SellerRegistration/{}Widget.js'.format(widget), props)

    return render_template('_react.html', component=rendered_component)
Beispiel #6
0
def index():
    no_js = 'no-js' in request.args

    comment_box = render_component(
        # An absolute path to the component
        os.path.join(BASE_DIR, 'static', 'jsx', 'CommentBox.jsx'),

        # The data that we use to render the component and mount it
        # on the client-side
        props={
            'comments': comments,
            'url': '/comment/',
            'pollInterval': 2000,
        },

        # Ensure that the source code is translated to JS from JSX & ES6/7.
        # This enables us to use future-facing JS across the client-side
        # and server-side
        translate=True,

        # If you do not intend to use React on the client-side, rendering
        # to static markup will optimise the generated markup
        to_static_markup=no_js)

    return render_template('index.html', comment_box=comment_box, no_js=no_js)
Beispiel #7
0
def indexView(request, template_name="core/index.html"):
    products = Product.objects.all()
    # page = Page.objects.all()
    # slides = ProductImage.objects.all()
    prod_arr = []
    for product in products:
        prod_arr.append({
            "id":
            product.id,
            "name":
            product.name,
            "slug":
            product.slug,
            "description":
            product.description,
            "weight":
            product.weight,
            "price":
            product.price,
            "product_images":
            product.get_first_image().get_image_url()
        })

    rendered = render_component(
        os.path.join(os.getcwd(), 'project', 'static', 'app', 'views',
                     'ServerRender.jsx'),
        {
            'is_server': [],
            'products': prod_arr
        },
        to_static_markup=True,
    )
    return render_to_response(template_name,
                              locals(),
                              context_instance=RequestContext(request))
def applications_list(applications):
    SCHEME = request.environ['wsgi.url_scheme']
    convert_url = url_for('main.convert_to_seller', _external=True, _scheme=SCHEME)
    reject_url = url_for('main.reject_application', _external=True, _scheme=SCHEME)
    revert_url = url_for('main.revert_application', _external=True, _scheme=SCHEME)
    preview_url = url_for('main.preview_application', _external=True, _scheme=SCHEME)
    search_url = url_for('main.search_applications', keyword='', _external=True, _scheme=SCHEME)
    delete_url = url_for('main.delete_application', id=0, _external=True, _scheme=SCHEME)
    edit_url = '{}://{}/{}/'.format(
        current_app.config['DM_HTTP_PROTO'],
        current_app.config['DM_MAIN_SERVER_NAME'],
        'sellers/application'
    )

    rendered_component = render_component(
        'bundles/ApplicationsAdmin/ApplicationsAdminWidget.js',
        {
            'applications': applications,
            'meta': {
                'url_convert_to_seller': convert_url,
                'url_reject_application': reject_url,
                'url_delete_application': delete_url,
                'url_revert_application': revert_url,
                'url_edit_application': edit_url,
                'url_preview': preview_url,
                'url_search_applications': search_url,
                'heading': 'Applications for approval',
            }
        }
    )

    return render_template(
        '_react.html',
        component=rendered_component
    )
Beispiel #9
0
def itemPage(**kwargs):
    store = {}
    props = kwargs['props']

    store['component'] = 'item.jsx'
    item_data = Search().getById([kwargs['item_id']])
    if item_data:
        item_data = item_data[0]
        categories = []
        for category in item_data['categories']:
            categories.append(Item.fetchCategory(name=category))
        item_data['categories'] = categories
        item_data = WebUtils.extendItemWebProperties([item_data])[0]
        # get reviews
        # get metadata info
    else:
        abort(404)

    # NOTE switchable: elasticsearch/DB
    #item_data = Item(kwargs['item_id']).getObj()
    #item_data.update(Item.getCustomProperties([item_data]))

    props.update({
        'item_data': item_data,
        'categories': Search.getAllSearchCategories(),
        'page': 'item'
    })
    store['props'] = props
    rendered = render_component(path(store['component']), props=props)
    return render_template('item.html',
                           rendered=rendered,
                           title=item_data['item_name'],
                           store=store)
def application_edit(id):
    application = data_api_client.get_application(id)['application']

    if 'supplier' in application:
        del application['supplier']

    if 'signed_agreements' in application:
        del application['signed_agreements']

    if 'assessed_domains' in application:
        del application['assessed_domains']

    rendered_component = render_component(
        'bundles/ApplicationsAdmin/ApplicationsAdminWidget.js',
        {
            'application': application,
            'meta': {
                'url_app_update': url_for('.update_application', application_id=id),
            }
        }
    )

    return render_template(
        '_react.html',
        component=rendered_component
    )
def application_diff(id):
    data = data_api_client.req.applications(id).admin().get()
    application = data['application']
    supplier = application.get('supplier', None)

    if 'supplier' in application:
        del application['supplier']

    if 'signed_agreements' in application:
        del application['signed_agreements']

    if 'assessed_domains' in application:
        del application['assessed_domains']

    rendered_component = render_component(
        'bundles/ApplicationsAdmin/ApplicationsAdminWidget.js',
        {
            'application': application,
            'meta': {
                'supplier': supplier,
                'url_app_update': url_for('.update_application', application_id=id),
            }
        }
    )

    return render_template(
        '_react.html',
        component=rendered_component
    )
Beispiel #12
0
    def test_favorite_panel(self):
        favorites = FavoriteSerializer(Favorite.objects.all(), many=True)

        html = str(render_component(
            'js/components/favorite-panel.js',
             to_static_markup=True,  # Don't output the react-id attributes
             props = {
               'favorites': favorites.data,
             }
        ))

        # Check presence of certain strings
        self.assertFalse('photo1.jpg' in html)
        self.assertTrue('photo2.jpg' in html)
        self.assertTrue('photo3.jpg' in html)

        # Check a specific text value
        pq = PyQuery(html)
        self.assertEqual(pq('.badge').text(), '2')

        # Compare HTML blocks
        self.assertHTMLEqual(
            pq('h4').outerHtml(),
            '<h4>Favorites <span class="badge">2</span></h4>'
        )
Beispiel #13
0
def index():
    config_file = os.path.join(BASE_DIR, 'example.webpack.js')

    component = os.path.join(BASE_DIR, 'app', 'CommentBox.jsx')

    props = {
        'comments': comments,
        'url': '/comment/',
    }

    rendered = render_component(component, props)

    webpack_context = {
        'component': component,
        'props_var': 'window.mountProps',
        'container': 'mount-container',
    }

    bundle = webpack(config_file, context=webpack_context)

    return render_template(
        'index.html',
        bundle=bundle,
        webpack_context=webpack_context,
        rendered=rendered,
    )
Beispiel #14
0
def index():
    config_file = os.path.join(BASE_DIR, 'example.webpack.js')

    component = os.path.join(BASE_DIR, 'app', 'CommentBox.jsx')

    props = {
        'comments': comments,
        'url': '/comment/',
    }

    rendered = render_component(component, props)

    webpack_context = {
        'component': component,
        'props_var': 'window.mountProps',
        'container': 'mount-container',
    }

    bundle = webpack(config_file, context=webpack_context)

    return render_template(
        'index.html',
        bundle=bundle,
        webpack_context=webpack_context,
        rendered=rendered,
    )
def render_create_application(token, data=None, errors=None):
    data = data or {}
    try:
        token_data = decode_user_token(token.encode())
    except InvalidToken:
        return render_template(
            'errors/500.html',
            error_message='Account creation invitation invalid or expired')

    if not token_data.get('email_address'):
        abort(503, 'Invalid email address')

    user_json = data_api_client.get_user(
        email_address=token_data['email_address'])

    if not user_json:
        rendered_component = render_component(
            'bundles/SellerRegistration/EnterPasswordWidget.js', {
                'form_options': {
                    'errors': errors
                },
                'enterPasswordForm': dict(token_data.items() + data.items()),
            })

        return render_template('_react.html', component=rendered_component)

    user = User.from_json(user_json)
    return render_template('auth/create_user_error.html',
                           data=token_data,
                           user=user), 400
Beispiel #16
0
def indexView(request, template_name="core/index.html"):
	products = Product.objects.all()
	# page = Page.objects.all()
	# slides = ProductImage.objects.all()
	prod_arr = []
	for product in products:
		prod_arr.append(
			{
				"id": product.id,
				"name": product.name,
				"slug": product.slug,
				"description": product.description,
				"weight": product.weight,
				"price": product.price,
				"product_images": product.get_first_image().get_image_url()
			}
		)

	rendered = render_component(
		os.path.join(os.getcwd(), 'project', 'static', 'app', 'views', 'ServerRender.jsx'),
		{
			'is_server': [],
			'products': prod_arr
		},
		to_static_markup=True,
	)
	return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Beispiel #17
0
def applications_list(applications):
    SCHEME = request.environ['wsgi.url_scheme']
    convert_url = url_for('main.convert_to_seller', _external=True, _scheme=SCHEME)
    reject_url = url_for('main.reject_application', _external=True, _scheme=SCHEME)
    revert_url = url_for('main.revert_application', _external=True, _scheme=SCHEME)
    preview_url = url_for('main.preview_application', _external=True, _scheme=SCHEME)
    search_url = url_for('main.search_applications', keyword='', _external=True, _scheme=SCHEME)
    delete_url = url_for('main.delete_application', id=0, _external=True, _scheme=SCHEME)
    edit_url = '{}://{}/{}/'.format(
        current_app.config['DM_HTTP_PROTO'],
        current_app.config['DM_MAIN_SERVER_NAME'],
        'sellers/application'
    )

    rendered_component = render_component(
        'bundles/ApplicationsAdmin/ApplicationsAdminWidget.js',
        {
            'applications': applications,
            'meta': {
                'url_convert_to_seller': convert_url,
                'url_reject_application': reject_url,
                'url_delete_application': delete_url,
                'url_revert_application': revert_url,
                'url_edit_application': edit_url,
                'url_preview': preview_url,
                'url_search_applications': search_url,
                'heading': 'Applications for approval',
            }
        }
    )

    return render_template(
        '_react.html',
        component=rendered_component
    )
def evidence_assessments_review(evidence_id=None):
    SCHEME = request.environ['wsgi.url_scheme']
    if evidence_id:
        evidence = data_api_client.req.evidence(evidence_id).get()['evidence']
    else:
        evidence = data_api_client.req.evidence().get()['evidence']

    rendered_component = render_component(
        'bundles/ApplicationsAdmin/EvidenceAssessmentsAdminWidget.js', {
            'evidence': evidence if evidence else None,
            'meta': {
                'url_approve':
                url_for('main.evidence_assessments_approve',
                        _external=True,
                        _scheme=SCHEME),
                'url_reject':
                url_for('main.evidence_assessments_reject',
                        _external=True,
                        _scheme=SCHEME),
                'server_name':
                current_app.config['DM_MAIN_SERVER_NAME']
            }
        })

    return render_template('_react.html', component=rendered_component)
Beispiel #19
0
def application_edit(id):
    application = data_api_client.get_application(id)['application']

    if 'supplier' in application:
        del application['supplier']

    if 'signed_agreements' in application:
        del application['signed_agreements']

    if 'assessed_domains' in application:
        del application['assessed_domains']

    rendered_component = render_component(
        'bundles/ApplicationsAdmin/ApplicationsAdminWidget.js',
        {
            'application': application,
            'meta': {
                'url_app_update': url_for('.update_application', application_id=id),
            }
        }
    )

    return render_template(
        '_react.html',
        component=rendered_component
    )
def index():
    no_js = 'no-js' in request.args

    comment_box = render_component(
        # An absolute path to the component
        os.path.join(BASE_DIR, 'static', 'jsx', 'CommentBox.jsx'),

        # The data that we use to render the component and mount it
        # on the client-side
        props={
            'comments': comments,
            'url': '/comment/',
            'pollInterval': 2000,
        },

        # Ensure that the source code is translated to JS from JSX & ES6/7.
        # This enables us to use future-facing JS across the client-side
        # and server-side
        translate=True,

        # If you do not intend to use React on the client-side, rendering
        # to static markup will optimise the generated markup
        to_static_markup=no_js
    )

    return render_template('index.html', comment_box=comment_box, no_js=no_js)
def render_create_application(token, data=None, errors=None):
    data = data or {}
    try:
        token_data = decode_user_token(token.encode())
    except InvalidToken:
        return render_template('errors/500.html', error_message='Account creation invitation invalid or expired')

    if not token_data.get('email_address'):
        abort(503, 'Invalid email address')

    user_json = data_api_client.get_user(email_address=token_data['email_address'])

    if not user_json:
        rendered_component = render_component(
            'bundles/SellerRegistration/EnterPasswordWidget.js', {
                'form_options': {
                    'errors': errors
                },
                'enterPasswordForm': dict(token_data.items() + data.items()),
            }
        )

        return render_template(
            '_react.html',
            component=rendered_component
        )

    user = User.from_json(user_json)
    return render_template(
        'auth/create_user_error.html',
        data=token_data,
        user=user), 400
def collaborate_create_project():
    form = DmForm()
    basename = url_for('.collaborate_create_project')
    props = {
        'form_options': {
            'csrf_token': form.csrf_token.current_token
        },
        'project': {
        },
        'basename': basename
    }

    if 'project' in session:
        props['projectForm'] = session['project']

    rendered_component = render_component('bundles/Collaborate/ProjectFormWidget.js', props)

    return render_template(
        '_react.html',
        breadcrumb_items=[
            {'link': url_for('main.index'), 'label': 'Home'},
            {'link': url_for('main.collaborate'), 'label': 'Collaborate'},
            {'label': 'Add project'}
        ],
        component=rendered_component
    )
Beispiel #23
0
def run_perf_test():
    render_component_times = []
    rendered_components = []

    iteration_count = 25

    for i in range(iteration_count):
        start = time.time()
        rendered_components.append(
            render_component(
                Components.PERF_TEST,
                props={'name': 'world'},
                translate=True,
                to_static_markup=True
            )
        )
        end = time.time()
        render_component_times.append(end - start)

    clean_bundle_root()

    for component in rendered_components:
        assert str(component) == '<span>Hello world</span>'

    print('Total time taken to render a component {iteration_count} times: {value}'.format(
        iteration_count=iteration_count,
        value=sum(render_component_times)
    ))
    print('Times: {}'.format(render_component_times))
    print('Max: {}'.format(max(render_component_times)))
    print('Min: {}'.format(min(render_component_times)))
    print('Mean: {}'.format(sum(render_component_times) / len(render_component_times)))
    print('Median: {}'.format(median(render_component_times)))
Beispiel #24
0
 def test_can_pass_props_when_rendering_a_bundled_jsx_component(self):
     bundle = bundle_component(Components.HELLO_WORLD_JSX, translate=True)
     asset = bundle.get_assets()[0]
     component = render_component(asset['path'],
                                  props={'name': 'world!'},
                                  to_static_markup=True)
     self.assertEqual(str(component), '<span>Hello world!</span>')
Beispiel #25
0
def application_diff(id):
    data = data_api_client.req.applications(id).admin().get()
    application = data['application']
    supplier = application.get('supplier', None)

    if 'supplier' in application:
        del application['supplier']

    if 'signed_agreements' in application:
        del application['signed_agreements']

    if 'assessed_domains' in application:
        del application['assessed_domains']

    rendered_component = render_component(
        'bundles/ApplicationsAdmin/ApplicationsAdminWidget.js',
        {
            'application': application,
            'meta': {
                'supplier': supplier,
                'url_app_update': url_for('.update_application', application_id=id),
            }
        }
    )

    return render_template(
        '_react.html',
        component=rendered_component
    )
Beispiel #26
0
def collaborate_create_project():
    form = DmForm()
    basename = url_for('.collaborate_create_project')
    props = {
        'form_options': {
            'csrf_token': form.csrf_token.current_token
        },
        'project': {
        },
        'basename': basename
    }

    if 'project' in session:
        props['projectForm'] = session['project']

    rendered_component = render_component('bundles/Collaborate/ProjectFormWidget.js', props)

    return render_template(
        '_react.html',
        breadcrumb_items=[
            {'link': url_for('main.index'), 'label': 'Home'},
            {'link': url_for('main.collaborate'), 'label': 'Collaborate'},
            {'label': 'Add project'}
        ],
        component=rendered_component
    )
    def test_rendered_components_which_are_bundled_have_access_to_their_bundle(
            self):
        bundled_component = render_component(Components.HELLO_WORLD_JS)
        self.assertRaises(ComponentWasNotBundled, bundled_component.get_bundle)

        bundled_component = render_component(Components.HELLO_WORLD_JS,
                                             bundle=True)
        self.assertIsInstance(bundled_component.get_bundle(), WebpackBundle)

        translated_component = render_component(Components.HELLO_WORLD_JS,
                                                translate=True)
        self.assertIsInstance(translated_component.get_bundle(), WebpackBundle)

        translated_component = render_component(Components.HELLO_WORLD_JS,
                                                bundle=True,
                                                translate=True)
        self.assertIsInstance(translated_component.get_bundle(), WebpackBundle)
 def test_can_get_a_components_serialized_props(self):
     component = render_component(
         Components.HELLO_WORLD_JSX,
         {
             'name': 'world!',
         },
     )
     self.assertEqual(component.props, '{"name": "world!"}')
Beispiel #29
0
def index():
    rendered = render_component(
        os.path.join(os.getcwd(), 'static', 'js', 'ToDo.jsx'),
        {"todosCount": 4},
        to_static_markup=True,
    )

    return render_template('index.html', rendered=rendered)
Beispiel #30
0
 def test_can_get_a_components_serialized_props(self):
     component = render_component(
         Components.HELLO_WORLD_JSX,
         {
             'name': 'world!',
         },
     )
     self.assertEqual(component.props, '{"name": "world!"}')
Beispiel #31
0
def index():
    component = render_component(
        os.path.join(os.getcwd(), 'static', 'TodoList.jsx'),
        props={'todos': TODOS},
        to_static_markup=False
    )

    return render_template('index.html', component=component)
Beispiel #32
0
def home(request):
	rendered = render_component(
		os.path.join(os.getcwd(), 'www', 'static', 'www', 'index.jsx'),
        {},
        to_static_markup=True,
    )

	return HttpResponse(rendered)
 def test_can_pass_props_when_rendering_a_bundled_jsx_component(self):
     bundle = bundle_component(Components.HELLO_WORLD_JSX, translate=True)
     asset = bundle.get_assets()[0]
     component = render_component(asset['path'], props={'name': 'world!'}, to_static_markup=True)
     self.assertEqual(
         str(component),
         '<span>Hello world!</span>'
     )
Beispiel #34
0
def home(request):
    filepath = os.path.join(os.path.dirname(__file__), 'ssr-build', 'home.js')
    js_context = {'foobar': 'baz'}
    content = render_component(filepath, js_context)
    return render(request, 'home.html', {
        'content': content,
        'js_context': js_context,
    })
Beispiel #35
0
 def test_can_render_a_component_to_a_string_with_props(self):
     component = render_component(
         Components.HELLO_WORLD_JSX,
         {'name': 'world!'},
     )
     markup = str(component)
     self.assertNotEqual(markup, '<span>Hello world!</span>')
     self.assertIn('Hello ', markup)
     self.assertIn('world!', markup)
 def test_bundled_components_can_render_script_elements_with_the_bundle_and_mount_js(
         self):
     component = render_component(Components.HELLO_WORLD_JS, bundle=True)
     self.assertEqual(
         component.render_js(),
         '\n<script src="' + component.bundle.get_urls()[0] +
         '"></script>\n<script>\n' + component.render_mount_js() +
         '\n</script>\n',
     )
def get_supplier(code):
    if not can_view_supplier_page(code):
        flash('buyer-role-required', 'error')
        return current_app.login_manager.unauthorized()

    supplier = DataAPIClient().get_supplier(code)['supplier']

    supplier["categories"] = list(set(
        price['serviceRole']['role'].replace('Junior ', '').replace('Senior ', '')  # Mind the white space after Junior
        for price in supplier['prices']
    ))

    supplier["caseStudies"] = []
    for casestudy_id in supplier['case_study_ids']:
        casestudy = DataAPIClient().get_case_study(casestudy_id)['caseStudy']
        supplier["caseStudies"].append(casestudy)

    owns_profile = user_owns_page(code)

    if request_wants_json():
        return jsonify(dict(supplier))

    # add business/authorized representative contact details
    if len(supplier['contacts']) > 0:
        supplier['contact_email'] = supplier.get('contact_email') or supplier['contacts'][0]['email']
        supplier['contact_phone'] = supplier.get('contact_phone') or supplier['contacts'][0]['phone']
        supplier['contact_name'] = supplier.get('contact_name') or supplier['contacts'][0]['name']
        supplier['representative'] = supplier.get('representative') or supplier['contacts'][0]['name']
    props = {"application": {key: supplier[key] for key in supplier if key not in ['disclosures']}}
    props['application']['case_study_url'] = '/case-study/'
    props['application']['public_profile'] = not owns_profile
    props['application']['recruiter'] = 'yes' if supplier.get('is_recruiter') == 'true' else 'no'
    props['application']['digital_marketplace_panel'] = False
    digital_marketplace_framework = data_api_client.req.frameworks('digital-marketplace').get()
    for framework in supplier.get('frameworks', []):
        if framework['framework_id'] == digital_marketplace_framework['frameworks']['id']:
            props['application']['digital_marketplace_panel'] = True
    props['application']['dsp_panel'] = len(supplier.get('domains', {'legacy': []})['legacy']) > 0
    props['basename'] = url_for('.get_supplier', code=code)
    props['form_options'] = {
        'action': "/sellers/edit",
        'submit_url': "/sellers/edit"
    }

    rendered_component = render_component('bundles/SellerRegistration/ApplicationPreviewWidget.js', props)

    return render_template(
        '_react.html',
        page_title=supplier.get('name'),
        component=rendered_component,
        breadcrumb_items=[
            {'link': url_for('main.index'), 'label': 'Home'},
            {'link': url_for('main.supplier_search'), 'label': 'Seller catalogue'},
            {'label': 'Seller details'}
        ],
        main_class='collapse' if not owns_profile else None
    )
 def test_can_render_a_component_to_a_string_with_props(self):
     component = render_component(
         Components.HELLO_WORLD_JSX,
         {'name': 'world!'},
     )
     markup = str(component)
     self.assertNotEqual(markup, '<span>Hello world!</span>')
     self.assertIn('Hello ', markup)
     self.assertIn('world!', markup)
def render_react(request, props={}):
    props['path'] = request.path
    react_html = render_component(
        os.path.join(settings.BASE_DIR, 'mysite', 'src', 'App.js'), props)

    return render(request, 'index.html', {
        'title': "Django-isomorphic-react",
        'react_html': react_html,
    })
Beispiel #40
0
 def get(self):
     rendered = render_component(
         os.path.join(os.getcwd(), 'local_files', 'checkmate-front-end',
                      'src', 'Register.js'),
         {},
         to_static_markup=False,
     )
     self.render(
         '/home/salieri/Desktop/checkers/dev/back-end/local_files/checkmate-front-end/public/index.html',
         rendered=rendered)
Beispiel #41
0
 def test_can_render_a_component_requiring_another_component(self):
     component = render_component(
         Components.HELLO_WORLD_JSX_WRAPPER,
         {
             'name': 'world!',
             'numbers': [1, 2, 3, 4, 5],
         },
         to_static_markup=True
     )
     self.assertEqual(str(component), '<div><span>Hello world!</span><span>10, 20, 30, 40, 50</span></div>')
Beispiel #42
0
def index(request):
    rendered = render_component(
        os.path.join(os.getcwd(), '..', 'frontend', 'src', 'index.js'),
        {
            'url': '/comment/',
        },
        to_static_markup=True,
    )

    return render(request, 'index.html', {'rendered': rendered})
 def get_ssr_context_data(self):
     ssr_context = render_component(self.ssr_script_path, {
         'clientManifest': self.ssr_client_manifest_path,
         'requestConfig': {
             'baseURL': self._get_ssr_base_url(),
             'headers': self._get_ssr_http_headers(),
         },
         'url': self._get_ssr_router_url(),
     }).markup
     return ssr_context
 def test_can_render_a_component_requiring_another_component(self):
     component = render_component(Components.HELLO_WORLD_JSX_WRAPPER, {
         'name': 'world!',
         'numbers': [1, 2, 3, 4, 5],
     },
                                  to_static_markup=True)
     self.assertEqual(
         str(component),
         '<div><span>Hello world!</span><span>10, 20, 30, 40, 50</span></div>'
     )
Beispiel #45
0
    def get(self):
        path_bits = self.request.path.split('/')
        event_id = urllib.unquote(path_bits[2])
        if not event_id:
            self.response.out.write('Need an event_id.')
            return

        # Load the db_event instead of the fb_event, as the db_event is likely to be in cache
        db_event = eventdata.DBEvent.get_by_id(event_id)
        if not db_event:
            self.abort(404)
        if not db_event.has_content():
            self.response.out.write('This event was %s.' % db_event.empty_reason)
            return

        self.display['displayable_event'] = DisplayableEvent(db_event)

        self.display['next'] = self.request.url
        self.display['show_mobile_app_promo'] = True
        self.jinja_env.filters['make_category_link'] = lambda lst: [jinja2.Markup('<a href="/?keywords=%s">%s</a>') % (x, x) for x in lst]

        self.display['canonical_url'] = 'http://%s/events/%s/%s' % (self._get_full_hostname(), db_event.id, slugify(db_event.name))

        self.display['email_suffix'] = '+event-%s' % db_event.id

        if self.request.get('new'):
            api_event = api.canonicalize_event_data(db_event, None, version=(1, 3))
            try:
                event_html = render_component(
                    path=os.path.abspath('dist/js-server/event.js'),
                    to_static_markup=True, # We don't need all the React data markup
                    props=dict(
                        event=api_event,
                    ))
            except (exceptions.RenderServerError, exceptions.ReactRenderingError):
                logging.exception('Error rendering React component')
                event_html = ''
            self.display['react_event_html'] = event_html

        if self.request.get('amp'):
            if self.display['displayable_event'].largest_cover:
                # Because minification interferes with html-validity when producing:
                # <meta name=viewport content=width=device-width,minimum-scale=1,initial-scale=1,maximum-scale=1,user-scalable=no>
                self.allow_minify = False
                event_amp_css_filename = os.path.join(os.path.dirname(__file__), '..', 'dist-includes/css/event-amp.css')
                event_amp_css = open(event_amp_css_filename).read()
                event_amp_css = re.sub(r'@-ms-viewport\s*{.*?}', '', event_amp_css)
                event_amp_css = re.sub(r'!important', '', event_amp_css)
                event_amp_css = event_amp_css.replace('url(..', 'url(/dist-' + self._get_static_version())
                self.display['event_amp_stylesheet'] = event_amp_css
                self.render_template('event_amp')
            else:
                self.abort(404)
        else:
            self.render_template('event')
Beispiel #46
0
def terms(**kwargs):
    store = {}
    props = kwargs['props']

    store['component'] = 'terms.jsx'
    store['props'] = props
    rendered = render_component(path(store['component']), props=props)
    return render_template('terms.html',
                           rendered=rendered,
                           title='Terms and Conditions',
                           store=store)
Beispiel #47
0
def index():
    rendered = render_component(
        os.path.join(os.getcwd(), 'static', 'js', 'CommentBox.jsx'),
        {
            'comments': comments,
            'url': '/comment/',
        },
        to_static_markup=True,
    )

    return render_template('index.html', rendered=rendered)
Beispiel #48
0
def index():
    rendered = render_component(
        os.path.join(os.getcwd(), 'static', 'js', 'CommentBox.jsx'),
        {
            'comments': comments,
            'url': '/comment/',
        },
        to_static_markup=True,
    )

    return render_template('index.html', rendered=rendered)
 def test_can_get_a_components_serialized_props(self):
     component = render_component(
         Components.HELLO_WORLD_JSX,
         props={
             'name': 'world!',
         },
         translate=True,
     )
     self.assertEqual(component.props, {'name': 'world!'})
     self.assertEqual(component.serialized_props, '{"name": "world!"}')
     self.assertEqual(component.render_props(), '{"name": "world!"}')
Beispiel #50
0
def react_serverside(request):
    """
    Renders the application on the server side.
    See https://github.com/markfinger/python-react
    """

    rendered = render_component(
        '{0}/example/exampleApp.jsx'.format(PROJECT_DIR),
    )

    return render(request, 'rest_messaging_js/react_serverside.html', {"rendered": rendered})
Beispiel #51
0
 def get(self):
     rendered = render_component(
     os.path.join(os.getcwd(), 'static', 'js', 'CommentBox.jsx'),
     {
         'comments': comments,
         'url': '/comments',
         'xsrf':self.xsrf_token
     },
     to_static_markup=False,
     )
     self.render('index.html', rendered=rendered)
def collaborate_code():
    rendered_component = render_component('bundles/Collaborate/CollaborateCodeWidget.js', {})
    return render_template(
        '_react.html',
        breadcrumb_items=[
            {'link': url_for('main.index'), 'label': 'Home'},
            {'link': url_for('main.collaborate'), 'label': 'Collaborate'},
            {'label': 'Open source library'}
        ],
        component=rendered_component,
        main_class='collapse'
    )
def home(request, template_name='core/home.html'):

  products = Product.objects.all()
  # # new_test = STATIC_ROOT
  # slides = Slide.objects.all()

  # for product in products:
  #   product.list_parametr = ProductParametr.objects.filter(product=product)

  # if request.method == 'POST':
  #   add_to_cart(request)

  # articles = Article.objects.all()
  # for art in articles:
  #   try:
  #     art.image = ArticleImage.objects.filter(article=art)[0]
  #   except:
  #     pass

  # pages = Page.objects.all()
  # for pag in pages:
  #   try:
  #     pag.image = PageImage.objects.filter(page=pag)
  #     pag.image = pag.image[0]
  #   except:
  #     pass

  # REACT server side render
  prod_arr = []
  for product in products:
    prod_arr.append(
      {
        "id": product.id,
        "name": product.name,
        "slug": product.slug,
        "description": product.description,
        # "weight": product.weight,
        # "price": product.price,
        # "product_images": product.get_image().get_image_url()
      }
    )

  rendered = render_component(
    os.path.join(os.getcwd(), 'project', 'static', 'app', 'src', 'App', 'App.js'),
    {
      'is_server': [],
      'products': prod_arr
    },
    to_static_markup=True,
  )

  return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Beispiel #54
0
def index(request):
    # return HttpResponse("Hello, world. You're at the polls index.")

    rendered = render_component(
        os.path.join(os.getcwd(), 'static', 'js', 'CommentBox.jsx'),
        {
            'comments': comments,
            'url': '/comments/comment/',
        },
        to_static_markup=True,
    )

    return render_to_response('index.html', {"rendered": rendered})
Beispiel #55
0
 def test_render_component_returns_a_rendered_component(self):
     component = render_component(
         Components.HELLO_WORLD_JSX,
         {
             'name': 'world!'
         },
         to_static_markup=True,
     )
     self.assertIsInstance(component, RenderedComponent)
     self.assertEqual(component.markup, '<span>Hello world!</span>')
     self.assertEqual(component.markup, str(component))
     if six.PY2:
         self.assertEqual(component.markup, unicode(component))
Beispiel #56
0
 def test_render_setting_is_respected(self):
     mock_settings = Conf()
     mock_settings.configure(RENDER=False)
     with mock.patch('react.conf.settings', mock_settings):
         rendered = render_component(
             Components.HELLO_WORLD_JSX,
             {'name': 'world!'},
             to_static_markup=True,
         )
         self.assertIsInstance(rendered, RenderedComponent)
         self.assertEqual(rendered.markup, '')
         self.assertEqual(str(rendered), '')
         self.assertEqual(rendered.props, '{"name": "world!"}')
def pre_rendered(request):
    photos = PhotoSerializer(Photo.objects.all(), many=True)
    favorites = FavoriteSerializer(Favorite.objects.all(), many=True)

    # Render HTML output by React server
    rendered_html = render_component(
        'js/components/album.js',
         props = {
           'photos': photos.data,
           'favorites': favorites.data,
         }
    )

    return render(request, 'pre-rendered.html', {'rendered_html': rendered_html})
    def get_context_data(self, **kwargs):
        context = super(Base, self).get_context_data(**kwargs)
        context["rendered"] = render_component(
            path = os.path.join(settings.BASE_DIR, 'assets/js/app.jsx'),

            props = {
                'name': 'Henry',
                'origin': 'server'
            },

            to_static_markup=True, 
        )

        return context
def start_seller_signup(applicant={}, errors=None):
    rendered_component = render_component(
        'bundles/SellerRegistration/SignupWidget.js', {
            'form_options': {
                'errors': errors
            },
            'yourInfoForm': applicant,
        }
    )

    return render_template(
        '_react.html',
        component=rendered_component
    )