Exemple #1
0
def lazy_img(ctx, image_url, placeholder_url, include_highres_image=False, optional_attributes=None):
    placeholder = static(path.join('img', placeholder_url))

    external_img = re.match(r'^https://', image_url, flags=re.I)

    # image could be external
    if not external_img:
        image = static(path.join('img', image_url))
    else:
        image = image_url

    if include_highres_image and not external_img:
        image_high_res = static(path.join('img', convert_to_high_res(image_url)))
        srcset = 'data-srcset="{image_high_res} 2x"'.format(image_high_res=image_high_res)
    else:
        srcset = ''

    if optional_attributes:
        class_name = optional_attributes.pop('class', 'lazy-image')
        alt_text = optional_attributes.pop('alt', '')
        attrs = ' '.join('%s="%s"' % (attr, val)
                         for attr, val in optional_attributes.items())
    else:
        class_name = 'lazy-image'
        alt_text = ''
        attrs = ''

    markup = ('<div class="lazy-image-container">'
              '<img class="{class_name}" src="{placeholder}" data-src="{image}" {srcset} alt="{alt_text}" {attrs}>'
              '<noscript>'
              '<img class="{class_name}" src="{image}" {srcset} alt="{alt_text}" {attrs}>'
              '</noscript>'
              '</div>').format(image=image, placeholder=placeholder, srcset=srcset, class_name=class_name, alt_text=alt_text, attrs=attrs)

    return jinja2.Markup(markup)
Exemple #2
0
    def test_works_for_default_lang(self, media_exists_mock):
        """Should output correct path for default lang always."""
        media_exists_mock.return_value = True
        assert self._render("en-US", "dino/head.png") == static("img/l10n/en-US/dino/head.png")
        assert self._render("en-US", "img/dino/head.png") == static("img/l10n/en-US/dino/head.png")

        assert self._render("en-US", "dino/does-not-exist.png") == static("img/l10n/en-US/dino/does-not-exist.png")
Exemple #3
0
 def test_works_for_other_lang(self, media_exists_mock):
     """Should use the request lang if file exists."""
     media_exists_mock.return_value = True
     assert self._render(
         'de', 'dino/head.png') == static('img/l10n/de/dino/head.png')
     assert self._render(
         'de', 'img/dino/head.png') == static('img/l10n/de/dino/head.png')
Exemple #4
0
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(path.join('img', url))
        url_high_res = static(path.join('img', 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 = ''

    # Use native srcset attribute for high res images
    markup = ('<img class="{class_name}" src="{url}" '
              'srcset="{url_high_res} 1.5x"'
              '{attrs}>').format(url=url,
                                 url_high_res=url_high_res,
                                 attrs=attrs,
                                 class_name=class_name)

    return jinja2.Markup(markup)
Exemple #5
0
def lazy_img(ctx, image_url, placeholder_url, include_highres_image=False, optional_attributes=None):
    placeholder = static(path.join('img', placeholder_url))
    image = static(path.join('img', image_url))

    if include_highres_image:
        image_high_res = static(path.join('img', convert_to_high_res(image_url)))
        srcset = 'data-srcset="{image_high_res} 2x"'.format(image_high_res=image_high_res)
    else:
        srcset = ''

    if optional_attributes:
        class_name = optional_attributes.pop('class', 'lazy-image')
        alt_text = optional_attributes.pop('alt', '')
        attrs = ' '.join('%s="%s"' % (attr, val)
                         for attr, val in optional_attributes.items())
    else:
        class_name = 'lazy-image'
        alt_text = ''
        attrs = ''

    markup = ('<div class="lazy-image-container">'
              '<img class="{class_name}" src="{placeholder}" data-src="{image}" {srcset} alt="{alt_text}" {attrs}>'
              '<noscript>'
              '<img class="{class_name}" src="{image}" {srcset} alt="{alt_text}" {attrs}>'
              '</noscript>'
              '</div>').format(image=image, placeholder=placeholder, srcset=srcset, class_name=class_name, alt_text=alt_text, attrs=attrs)

    return jinja2.Markup(markup)
Exemple #6
0
    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'))
Exemple #7
0
    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'))
Exemple #8
0
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 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))
Exemple #10
0
    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]
        assert 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]
        assert 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]
        assert 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]
        assert self._render("es", "dino/head.png") == static("img/l10n/es-ES/dino/head.png")
Exemple #11
0
    def test_file_not_checked_for_default_lang(self, media_exists_mock):
        """
        Should not check filesystem for default lang, but should for others.
        """
        assert self._render("en-US", "dino/does-not-exist.png") == static("img/l10n/en-US/dino/does-not-exist.png")
        assert 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_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')
Exemple #13
0
    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')
Exemple #14
0
def lazy_img(ctx,
             image_url,
             placeholder_url,
             include_highres_image=False,
             optional_attributes=None,
             highres_image_url=None):
    placeholder = static(placeholder_url)

    external_img = re.match(r'^https?://', image_url, flags=re.I)

    if include_highres_image and not external_img:
        image_high_res = static(convert_to_high_res(image_url))
        srcset = f'data-srcset="{image_high_res} 2x"'
    else:
        srcset = ''

    # image could be external
    if not external_img:
        image_url = static(image_url)

    if highres_image_url:
        srcset = f'data-srcset="{highres_image_url} 2x"'

    if optional_attributes:
        class_name = optional_attributes.pop('class', 'lazy-image')
        alt_text = optional_attributes.pop('alt', '')
        attrs = ' '.join('%s="%s"' % (attr, val)
                         for attr, val in optional_attributes.items())
    else:
        class_name = 'lazy-image'
        alt_text = ''
        attrs = ''

    markup = (
        f'<div class="lazy-image-container">'
        f'<img class="{class_name}" src="{placeholder}" data-src="{image_url}" {srcset} alt="{alt_text}" {attrs}>'
        f'<noscript>'
        f'<img class="{class_name}" src="{image_url}" {srcset} alt="{alt_text}" {attrs}>'
        f'</noscript>'
        f'</div>')

    return jinja2.Markup(markup)
    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'))
Exemple #16
0
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)
Exemple #17
0
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)
Exemple #18
0
    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'))
Exemple #19
0
def high_res_img(ctx, url, optional_attributes=None):
    if optional_attributes and optional_attributes.pop("l10n", False) is True:
        url = _strip_img_prefix(url)
        url_high_res = convert_to_high_res(url)
        url = l10n_img(ctx, url)
        url_high_res = l10n_img(ctx, url_high_res)
    else:
        url_high_res = convert_to_high_res(url)
        url = static(url)
        url_high_res = static(url_high_res)

    if optional_attributes:
        class_name = optional_attributes.pop("class", "")
        attrs = " " + " ".join(f'{attr}="{val}"' for attr, val in optional_attributes.items())
    else:
        class_name = ""
        attrs = ""

    # Use native srcset attribute for high res images
    markup = f'<img class="{class_name}" src="{url}" srcset="{url_high_res} 1.5x"{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(path.join('img', url))
        url_high_res = static(path.join('img', 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 = ''

    # Use native srcset attribute for high res images
    markup = ('<img class="{class_name}" src="{url}" '
              'srcset="{url_high_res} 1.5x"'
              '{attrs}>').format(url=url, url_high_res=url_high_res,
                                 attrs=attrs, class_name=class_name)

    return jinja2.Markup(markup)
Exemple #21
0
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)
Exemple #22
0
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)
Exemple #23
0
def platform_img(ctx, url, optional_attributes=None):
    url = _strip_img_prefix(url)
    optional_attributes = optional_attributes or {}
    img_urls = {}
    platforms = optional_attributes.pop('platforms', ALL_FX_PLATFORMS)
    add_high_res = optional_attributes.pop('high-res', False)
    is_l10n = optional_attributes.pop('l10n', False)

    for platform in 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.items():
        if is_l10n:
            image = l10n_img_file_name(ctx, image)
        else:
            image = path.join('img', 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.items())

    # 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)
Exemple #24
0
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 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)
Exemple #26
0
def platform_img(ctx, url, optional_attributes=None):
    optional_attributes = optional_attributes or {}
    img_urls = {}
    platforms = optional_attributes.pop("platforms", ALL_FX_PLATFORMS)
    add_high_res = optional_attributes.pop("high-res", False)
    is_l10n = optional_attributes.pop("l10n", False)

    for platform in 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.items():
        if is_l10n:
            image = l10n_img_file_name(ctx, _strip_img_prefix(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(f'{attr}="{val}"' for attr, val in img_attrs.items())

    # 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 platform_img(ctx, url, optional_attributes=None):
    optional_attributes = optional_attributes or {}
    img_urls = {}
    platforms = optional_attributes.pop('platforms', ALL_FX_PLATFORMS)
    add_high_res = optional_attributes.pop('high-res', False)
    is_l10n = optional_attributes.pop('l10n', False)

    for platform in 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)
        else:
            image = path.join('img', 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)
Exemple #28
0
 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
     assert self._render(
         'is', 'dino/head.png') == static('img/l10n/en-US/dino/head.png')
Exemple #29
0
 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'))
Exemple #30
0
 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'))