def high_res_img(ctx, url, optional_attributes=None): url_high_res = convert_to_high_res(url) if optional_attributes and optional_attributes.pop('l10n', False) is True: url = l10n_img(ctx, url) url_high_res = l10n_img(ctx, url_high_res) else: url = static(url) url_high_res = static(url_high_res) if optional_attributes: attrs = ' ' + ' '.join('%s="%s"' % (attr, val) for attr, val in optional_attributes.items()) else: attrs = '' # Don't download any image until the javascript sets it based on # data-src so we can do high-dpi detection. If no js, show the # normal-res version. markup = ('<img class="js" src="" data-processed="false" ' 'data-src="{url}" data-high-res="true" ' 'data-high-res-src="{url_high_res}"{attrs}><noscript>' '<img src="{url}"{attrs}></noscript>').format(url=url, url_high_res=url_high_res, attrs=attrs) return jinja2.Markup(markup)
def high_res_img(ctx, url, optional_attributes=None): url_high_res = convert_to_high_res(url) if optional_attributes and optional_attributes.pop('l10n', False) is True: url = l10n_img(ctx, url) url_high_res = l10n_img(ctx, url_high_res) else: url = static(url) url_high_res = static(url_high_res) if optional_attributes: class_name = optional_attributes.pop('class', '') attrs = ' ' + ' '.join('%s="%s"' % (attr, val) for attr, val in optional_attributes.items()) else: class_name = '' attrs = '' # Don't download any image until the javascript sets it based on # data-src so we can do high-dpi detection. If no js, show the # normal-res version. markup = ('<img class="js {class_name}" src="" data-processed="false" ' 'data-src="{url}" data-high-res="true" ' 'data-high-res-src="{url_high_res}"{attrs}><noscript>' '<img class="{class_name}" src="{url}"{attrs}>' '</noscript>').format(url=url, url_high_res=url_high_res, attrs=attrs, class_name=class_name) return jinja2.Markup(markup)
def test_works_for_default_lang(self, media_exists_mock): """Should output correct path for default lang always.""" media_exists_mock.return_value = True eq_(self._render('en-US', 'dino/head.png'), static('img/l10n/en-US/dino/head.png')) eq_(self._render('en-US', 'dino/does-not-exist.png'), static('img/l10n/en-US/dino/does-not-exist.png'))
def platform_img(ctx, url, optional_attributes=None): optional_attributes = optional_attributes or {} img_urls = {} add_high_res = optional_attributes.pop('high-res', False) is_l10n = optional_attributes.pop('l10n', False) for platform in ALL_FX_PLATFORMS: img_urls[platform] = add_string_to_image_url(url, platform) if add_high_res: img_urls[platform + '-high-res'] = convert_to_high_res(img_urls[platform]) img_attrs = {} for platform, image in img_urls.iteritems(): if is_l10n: image = l10n_img_file_name(ctx, image) if find_static(image): key = 'data-src-' + platform img_attrs[key] = static(image) if add_high_res: img_attrs['data-high-res'] = 'true' img_attrs.update(optional_attributes) attrs = ' '.join('%s="%s"' % (attr, val) for attr, val in img_attrs.iteritems()) # Don't download any image until the javascript sets it based on # data-src so we can do platform detection. If no js, show the # windows version. markup = ('<img class="platform-img js" src="" data-processed="false" {attrs}>' '<noscript><img class="platform-img win" src="{win_src}" {attrs}>' '</noscript>').format(attrs=attrs, win_src=img_attrs['data-src-windows']) return jinja2.Markup(markup)
def l10n_img(ctx, url): """Output the url to a localized image. Uses the locale from the current request. Checks to see if the localized image exists, and falls back to the image for the default locale if not. Examples ======== In Template ----------- {{ l10n_img('firefoxos/screenshot.png') }} For en-US this would output: {{ static('img/l10n/en-US/firefox/screenshot.png') }} For fr this would output: {{ static('img/l10n/fr/firefox/screenshot.png') }} If that file did not exist it would default to the en-US version (if en-US was the default language for this install). In the Filesystem ----------------- Put files in folders like the following:: $ROOT/media/img/l10n/en-US/firefoxos/screenshot.png $ROOT/media/img/l10n/fr/firefoxos/screenshot.png """ return static(l10n_img_file_name(ctx, url))
def test_js_bundle_files_debug_false(self): """ When DEBUG is off the bundle should return a single minified filename. """ bundle = 'partners_desktop' filename = static('js/%s-bundle.js' % bundle) bundle_file = json.loads(fx_views.get_js_bundle_files(bundle)) self.assertEqual(len(bundle_file), 1) self.assertEqual(bundle_file[0], filename)
def test_file_not_checked_for_default_lang(self, media_exists_mock): """ Should not check filesystem for default lang, but should for others. """ eq_(self._render('en-US', 'dino/does-not-exist.png'), static('img/l10n/en-US/dino/does-not-exist.png')) ok_(not media_exists_mock.called) self._render('is', 'dino/does-not-exist.png') media_exists_mock.assert_called_once_with('img', 'is', 'dino/does-not-exist.png')
def test_js_bundle_files_debug_true(self): """ When DEBUG is on the bundle should return the individual files with the STATIC_URL. """ bundle = 'partners_desktop' files = settings.PIPELINE_JS[bundle]['source_filenames'] files = [static(f) for f in files] self.assertEqual(files, json.loads(fx_views.get_js_bundle_files(bundle)))
def get_js_bundle_files(bundle): """ Return a JSON string of the list of file names for lazy loaded javascript. """ bundle = settings.PIPELINE_JS[bundle] if settings.DEBUG: items = bundle['source_filenames'] else: items = (bundle['output_filename'], ) return json.dumps([static(i) for i in items])
def tabzilla_css_redirect(r): packer = Packager() tabzilla_package = packer.package_for('css', 'tabzilla') if not settings.DEBUG: file_path = tabzilla_package.output_filename else: default_collector.collect() paths = packer.compile(tabzilla_package.paths) file_path = paths[0] return static(file_path)
def test_latam_spanishes_fallback_to_european_spanish(self, media_exists_mock): """Should use es-ES image when file doesn't exist for lang.""" media_exists_mock.side_effect = [False, True] eq_(self._render('es-AR', 'dino/head.png'), static('img/l10n/es-ES/dino/head.png')) media_exists_mock.reset_mock() media_exists_mock.side_effect = [False, True] eq_(self._render('es-CL', 'dino/head.png'), static('img/l10n/es-ES/dino/head.png')) media_exists_mock.reset_mock() media_exists_mock.side_effect = [False, True] eq_(self._render('es-MX', 'dino/head.png'), static('img/l10n/es-ES/dino/head.png')) media_exists_mock.reset_mock() media_exists_mock.side_effect = [False, True] eq_(self._render('es', 'dino/head.png'), static('img/l10n/es-ES/dino/head.png'))
def get_js_bundle_files(bundle): """ Return a JSON string of the list of file names for lazy loaded javascript. """ bundle = settings.PIPELINE_JS[bundle] if settings.DEBUG: items = bundle['source_filenames'] else: items = (bundle['output_filename'],) return json.dumps([static(i) for i in items])
def gravatar(arg, size=80): if isinstance(arg, User): email = arg.email else: # Treat as email email = arg return '{url}/avatar/{email_hash}?{options}'.format( url=GRAVATAR_URL, email_hash=md5(email.lower()).hexdigest(), options=urllib.urlencode({'s': unicode(size), 'd': absolutify(static('img/avatar.jpg'))}) )
def browserid_request_args(request): request_args = { 'privacyPolicy': 'http://www.mozilla.org/en-US/privacy-policy.html', 'siteName': _('Firefox Flicks'), 'termsOfService': reverse('flicks.base.rules'), } if request.is_secure(): request_args['siteLogo'] = static('img/flicks-logo-180.png') return {'browserid_request_args': request_args}
def gravatar(arg, size=80): if isinstance(arg, User): email = arg.email else: # Treat as email email = arg return '{url}/avatar/{email_hash}?{options}'.format( url=GRAVATAR_URL, email_hash=md5(email.lower()).hexdigest(), options=urllib.urlencode({ 's': unicode(size), 'd': absolutify(static('img/avatar.jpg')) }))
def get_abs_static(path, request): path = static(path) prefix = request.is_secure() and 'https' or 'http' if path.startswith('/') and not path.startswith('//'): # e.g. '/media/foo.png' root_url = get_base_url(request) path = root_url + path if path.startswith('//'): path = '%s:%s' % (prefix, path) assert path.startswith('http://') or path.startswith('https://') return path
def _request_args(): from django.conf import settings from funfactory.helpers import static from tower import ugettext_lazy as _lazy args = { 'privacyPolicy': 'http://www.mozilla.org/en-US/privacy-policy.html', 'siteName': _lazy('Firefox Flicks'), 'termsOfService': reverse_lazy('flicks.base.rules'), } if settings.SITE_URL.startswith('https'): args['siteLogo'] = static('img/flicks-logo-180.png') return args
def _request_args(): from django.conf import settings from funfactory.helpers import static from tower import ugettext_lazy as _lazy args = { "privacyPolicy": "http://www.mozilla.org/en-US/privacy-policy.html", "siteName": _lazy("Firefox Flicks"), "termsOfService": reverse_lazy("flicks.base.rules"), } if settings.SITE_URL.startswith("https"): args["siteLogo"] = static("img/flicks-logo-180.png") return args
def abs_static(context, path): """Make sure we always return a FULL absolute URL that starts with 'http'. """ path = static(path) prefix = context['request'].is_secure() and 'https' or 'http' if path.startswith('/') and not path.startswith('//'): # e.g. '/media/foo.png' root_url = '%s://%s' % (prefix, RequestSite(context['request']).domain) path = root_url + path if path.startswith('//'): path = '%s:%s' % (prefix, path) assert path.startswith('http://') or path.startswith('https://') return path
def holiday_calendars(request, template='mozorg/projects/holiday-calendars.html'): """Generate the table of holiday calendars from JSON.""" calendars = [] json_file = find_static('caldata/calendars.json') with open(json_file) as calendar_data: calendars = json.load(calendar_data) letters = set() for calendar in calendars: letters.add(calendar['country'][:1]) data = { 'calendars': sorted(calendars, key=lambda k: k['country']), 'letters': sorted(letters), 'CALDATA_URL': static('caldata/') } return l10n_utils.render(request, template, data)
def l10n_css(ctx): """ Output the URL to a locale-specific stylesheet if exists. Examples ======== In Template ----------- {{ l10n_css() }} For a locale that has locale-specific stylesheet, this would output: <link rel="stylesheet" media="screen,projection,tv" href="{{ STATIC_URL }}css/l10n/{{ LANG }}/intl.css"> For a locale that doesn't have any locale-specific stylesheet, this would output nothing. In the Filesystem ----------------- Put files in folders like the following:: $ROOT/media/css/l10n/en-US/intl.css $ROOT/media/css/l10n/fr/intl.css """ locale = getattr(ctx['request'], 'locale', 'en-US') if _l10n_media_exists('css', locale, 'intl.css'): markup = ('<link rel="stylesheet" media="screen,projection,tv" href=' '"%s">' % static(path.join('css', 'l10n', locale, 'intl.css'))) else: markup = '' return jinja2.Markup(markup)
def thumbnail_url(self): return (self.thumbnail.url if self.thumbnail else static('img/video-blank.jpg'))
def test_works_for_other_lang(self, media_exists_mock): """Should use the request lang if file exists.""" media_exists_mock.return_value = True eq_(self._render('de', 'dino/head.png'), static('img/l10n/de/dino/head.png'))
def test_defaults_when_lang_file_missing(self, media_exists_mock): """Should use default lang when file doesn't exist for lang.""" media_exists_mock.return_value = False eq_(self._render('is', 'dino/head.png'), static('img/l10n/en-US/dino/head.png'))