def test_gettext_with_variables(self):
     self.assertEqual(i18n.gettext('foo %(foo)s'), u'foo %(foo)s')
     self.assertEqual(
         i18n.gettext('foo %(foo)s') % {'foo': 'bar'},
         u'foo bar'
     )
     self.assertEqual(i18n.gettext('foo %(foo)s', foo='bar'), u'foo bar')
Exemplo n.º 2
0
 def ComputeDownloadInfo(self, d):
   display_os = DISPLAY_OS[d['os']]
   short_display_os = SHORT_DISPLAY_OS[d['os']]
   version = d['ver']
   d['display_os'] = i18n.gettext(display_os)
   d['short_os'] = i18n.gettext(short_display_os)
   d['os_logo'] = OS_LOGOS[d['os']]
   d['url'] =  DOWNLOAD_BASE_URL + d['name']
Exemplo n.º 3
0
 def ComputeDownloadInfo(self, d):
   display_os = DISPLAY_OS[d['os']]
   short_display_os = SHORT_DISPLAY_OS[d['os']]
   version = d['ver']
   if version < '1.2':
     download_base_url = DOWNLOAD_BASE_URL_OLD
   else:
     download_base_url = DOWNLOAD_BASE_URL
   d['display_os'] = i18n.gettext(display_os)
   d['short_os'] = i18n.gettext(short_display_os)
   d['os_logo'] = OS_LOGOS[d['os']]
   d['url'] = download_base_url + d['name']
Exemplo n.º 4
0
    def __init__(self, config):
        """Initializes the Jinja2 object.

        example_config = {
            'environment_args': {'extensions': JINJA2_EXTENSIONS,
                                 'autoescape': config.settings.getboolean('jinja2_env_autoescape',
                                                                          section=FRONTEND),},
            'theme_base_template_path': config.settings.getlist('theme_base_template_path', section=FRONTEND),
            'enable_i18n': 'jinja2.ext.i18n' in JINJA2_EXTENSIONS,
            'global_vars': {},
            'filters': {},
            'tests': {},
        }
        """
        try:
            config['environment_args']['loader'] = jinja2.FileSystemLoader(config['theme_base_template_path'])
        except KeyError:
            config['environment_args'] = {
                'loader': jinja2.FileSystemLoader(config['theme_base_template_path'])
            }

        # Initialize the environment.
        self.environment = jinja2.Environment(**config['environment_args'])

        self.environment.globals.update({'getattr': getattr})
        try:
            if isinstance(config['global_vars'], dict):
                self.environment.globals.update(config['global_vars'])
        except KeyError:
            # No global vars set in config
            pass

        try:
            if isinstance(config['filters'], dict):
                self.environment.filters.update(config['filters'])
        except KeyError:
            # No filters set in config
            pass

        try:
            if isinstance(config['tests'], dict):
                self.environment.filters.update(config['tests'])
        except KeyError:
            # No tests set in config
            pass

        if config['enable_i18n']:
            # Install i18n.
            from webapp2_extras import i18n
            self.environment.install_gettext_callables(
                lambda x: i18n.gettext(x),
                lambda s, p, n: i18n.ngettext(s, p, n),
                newstyle=True)
            self.environment.filters.update({
                'format_date':      i18n.format_date,
                'format_time':      i18n.format_time,
                'format_datetime':  i18n.format_datetime,
                'format_timedelta': i18n.format_timedelta,
            })
Exemplo n.º 5
0
def add_to_model(model):
    # get the games
    script = []
    operations = dict()
    #q = model.Game.all()
    operations['two_factor_multiplication_upto_9'] = {
        'id': 'two_factor_multiplication_upto_9',
        'title': i18n.gettext('Multiply'),
        'defaultDisplay': '? x ?',
    }
    operations['additions_substractions'] = {
        'id': 'additions_substractions',
        'title': i18n.gettext('Add & Substract'),
        'defaultDisplay': '? + ?'
    }

    model['operations'] = operations
    model['operations_json'] = json.dumps(operations)
Exemplo n.º 6
0
def add_to_model(model):
            # get the games
    script = []
    operations = dict()
    #q = model.Game.all()
    operations['two_factor_multiplication_upto_9'] = {
            'id': 'two_factor_multiplication_upto_9',
            'title' : i18n.gettext('Multiply'),
            'defaultDisplay': '? x ?',
        } 
    operations['additions_substractions'] = {
        'id' : 'additions_substractions',
        'title' : i18n.gettext('Add & Substract'),
        'defaultDisplay' : '? + ?'
    }
    
    model['operations'] = operations;
    model['operations_json'] = json.dumps(operations)
Exemplo n.º 7
0
    def __init__(self, app, config=None):
        """Initializes the Jinja2 object.

        :param app:
            A :class:`webapp2.WSGIApplication` instance.
        :param config:
            A dictionary of configuration values to be overridden. See
            the available keys in :data:`default_config`.
        """
        self.config = config = app.config.load_config(
            self.config_key,
            default_values=default_config,
            user_values=config,
            required_keys=None,
        )
        kwargs = config["environment_args"].copy()
        enable_i18n = "jinja2.ext.i18n" in kwargs.get("extensions", [])

        if "loader" not in kwargs:
            template_path = config["template_path"]
            compiled_path = config["compiled_path"]
            use_compiled = not app.debug or config["force_compiled"]

            if compiled_path and use_compiled:
                # Use precompiled templates loaded from a module or zip.
                kwargs["loader"] = _jinja2.ModuleLoader(compiled_path)
            else:
                # Parse templates for every new environment instances.
                kwargs["loader"] = _jinja2.FileSystemLoader(template_path)

        # Initialize the environment.
        env = _jinja2.Environment(**kwargs)

        if config["globals"]:
            env.globals.update(config["globals"])

        if config["filters"]:
            env.filters.update(config["filters"])

        if enable_i18n:
            # Install i18n.
            from webapp2_extras import i18n

            env.install_gettext_callables(
                lambda x: i18n.gettext(x),
                lambda s, p, n: i18n.ngettext(s, p, n),
                newstyle=True,
            )
            env.filters.update({
                "format_date": i18n.format_date,
                "format_time": i18n.format_time,
                "format_datetime": i18n.format_datetime,
                "format_timedelta": i18n.format_timedelta,
            })

        self.environment = env
Exemplo n.º 8
0
    def get(self):
        
        user = users.get_current_user()
        usrlocale = UserLocale.gql("WHERE user = :u",u=user).get()
        dateformat = ''
        lastaddeddate = None
        qdat = DateS.gql('ORDER BY __key__ DESC').get()
        
        if qdat:
            lastaddeddate = qdat.dat
            
        if usrlocale == None:
            locale=self.browser_locale()
            i18n.get_i18n().set_locale(locale)
            datLoc = I18n(self.request)
            datLoc.set_locale(locale)
            jqdatelocale = locale.replace('_', '-')
            if locale == 'en_US':
                dateformat = 'MM/dd/yyyy'
        else:
            locale = usrlocale.locale
            datelocale = usrlocale.datelocale
            i18n.get_i18n().set_locale(locale)
            jqdatelocale = datelocale.replace('_', '-')
            datLoc = I18n(self.request)       
            datLoc.set_locale(datelocale)
            dateformat = usrlocale.dateformat
            if dateformat == '' and usrlocale.datelocale =='en':
                dateformat = 'MM/dd/yyyy'
            
        if jqdatelocale not in SupportedLocales.locales:
            jqdatelocale = None
            
        if dateformat == '' or dateformat == None:
            dateformat = 'short'
            jqdateformat = None
        elif locale == 'en_US':
            jqdateformat = common.isotojqformat(dateformat)
        else:
            jqdateformat = common.isotojqformat(usrlocale.dateformat)

        message = i18n.gettext('Hello, world!')
        context = {
                    'message': message,
                    'thetime': datLoc.format_datetime(
                                        datetime.now(),
                                        format=dateformat),
                    'locale':jqdatelocale,
                    'dateformat':jqdateformat,
                    'datefromdb':datLoc.format_date(
                                        lastaddeddate,
                                        format=dateformat)
                  }
        self.render_response('tplhello.html', **context)
Exemplo n.º 9
0
    def __init__(self, app, config=None):
        """Initializes the Jinja2 object.

        :param app:
            A :class:`webapp2.WSGIApplication` instance.
        :param config:
            A dictionary of configuration values to be overridden. See
            the available keys in :data:`default_config`.
        """
        self.config = config = app.config.load_config(
            self.config_key,
            default_values=default_config,
            user_values=config,
            required_keys=None
        )
        kwargs = config['environment_args'].copy()
        enable_i18n = 'jinja2.ext.i18n' in kwargs.get('extensions', [])

        if 'loader' not in kwargs:
            template_path = config['template_path']
            compiled_path = config['compiled_path']
            use_compiled = not app.debug or config['force_compiled']

            if compiled_path and use_compiled:
                # Use precompiled templates loaded from a module or zip.
                kwargs['loader'] = _jinja2.ModuleLoader(compiled_path)
            else:
                # Parse templates for every new environment instances.
                kwargs['loader'] = _jinja2.FileSystemLoader(template_path)

        # Initialize the environment.
        env = _jinja2.Environment(**kwargs)

        if config['globals']:
            env.globals.update(config['globals'])

        if config['filters']:
            env.filters.update(config['filters'])

        if enable_i18n:
            # Install i18n.
            from webapp2_extras import i18n
            env.install_gettext_callables(
                lambda x: i18n.gettext(x),
                lambda s, p, n: i18n.ngettext(s, p, n),
                newstyle=True)
            env.filters.update({
                'format_date':      i18n.format_date,
                'format_time':      i18n.format_time,
                'format_datetime':  i18n.format_datetime,
                'format_timedelta': i18n.format_timedelta,
            })

        self.environment = env
Exemplo n.º 10
0
def get_error(code, key = None, message = None, *args):
    if message:
        text = message
    elif key: 
        text = settings.API_CODES[code][key]
    else:
        text = settings.API_CODES[code]
    # try to translate the text
    try:
      text = i18n.gettext(text)
    except Exception:
      pass
    return {'code' : code, 'message' : text }
Exemplo n.º 11
0
def get_error(code, key=None, message=None, *args):
    if message:
        text = message
    elif key:
        text = settings.API_CODES[code][key]
    else:
        text = settings.API_CODES[code]
    # try to translate the text
    if not message:
        try:
            text = i18n.gettext(text)
        except Exception:
            pass
    return {'code': code, 'message': text}
Exemplo n.º 12
0
def get_error(code, key = None, message = None):
    if message:
        text = message
    elif key: 
        text = settings.API_CODES[code][key]
    
    if not message and not key:
        text = settings.API_CODES[code]
    
    # try to translate the text
    try:
      text = i18n.gettext(text)
    except Exception:
      pass
    
    return {'code' : code, 'response' : text }
Exemplo n.º 13
0
    def __init__(self, app):
        config = app.config[__name__]
        kwargs = config['environment_args'].copy()
        enable_i18n = 'jinja2.ext.i18n' in kwargs.get('extensions', [])

        if 'loader' not in kwargs:
            template_path = config['template_path']
            compiled_path = config['compiled_path']
            use_compiled = not app.debug or config['force_compiled']

            if compiled_path and use_compiled:
                # Use precompiled templates loaded from a module or zip.
                kwargs['loader'] = jinja2.ModuleLoader(compiled_path)
            else:
                # Parse templates for every new environment instances.
                kwargs['loader'] = jinja2.FileSystemLoader(template_path)

        # Initialize the environment.
        env = jinja2.Environment(**kwargs)

        if config['globals']:
            env.globals.update(config['globals'])

        if config['filters']:
            env.filters.update(config['filters'])

        if enable_i18n:
            # Install i18n.
            from webapp2_extras import i18n
            env.install_gettext_callables(
                lambda x: i18n.gettext(x),
                lambda s, p, n: i18n.ngettext(s, p, n),
                newstyle=True)
            env.filters.update({
                'format_date':      i18n.format_date,
                'format_time':      i18n.format_time,
                'format_datetime':  i18n.format_datetime,
                'format_timedelta': i18n.format_timedelta,
            })

        self.environment = env
Exemplo n.º 14
0
 def test_gettext_with_variables(self):
     self.assertEqual(i18n.gettext('foo %(foo)s'), u'foo %(foo)s')
     self.assertEqual(
         i18n.gettext('foo %(foo)s') % {'foo': 'bar'}, u'foo bar')
     self.assertEqual(i18n.gettext('foo %(foo)s', foo='bar'), u'foo bar')
Exemplo n.º 15
0
 def test_gettext(self):
     self.assertEqual(i18n.gettext('foo'), u'foo')
Exemplo n.º 16
0
def add_to_model(model):
    model['strings'] = dict();
    model['strings']['login_justification'] = i18n.gettext('... so you can track your progress')
    model['strings']['signin_with_google'] = i18n.gettext('Sign in with <b>Google</b>')    
    model['strings']['title'] = i18n.gettext('Math Dash - timed math practice')
    model['strings']['points'] = i18n.gettext('points')
    model['strings']['seconds_remaining'] = i18n.gettext('seconds remaining')
    model['strings']['count_faster'] = i18n.gettext('count faster')
    model['strings']['how_am_i_doing'] = i18n.gettext('How am I doing?')
    model['strings']['challenges'] = i18n.gettext('Challenges')
    model['strings']['not_signed_in'] = i18n.gettext('You\'re not signed-in.  Math Dash will not record your points')
    model['strings']['just_practice'] = i18n.gettext('Just practice')
    model['strings']['sign_out'] = i18n.gettext('Sign Out')
    model['strings']['sign_me_in'] = i18n.gettext('Sign-in now and record my points')
    model['strings']['well_done'] = i18n.gettext('Well done!')
    model['strings']['giving_up_already'] = i18n.gettext('Giving up already?')
    model['strings']['result_stats'] = i18n.gettext('You answered <span id="questions_total"></span> questions in <span id="time_spent"></span> seconds and got <span id="questions_correct"></span> right.')
    model['strings']['main_page'] = i18n.gettext('Main Page')
    
    model['strings_json'] = json.dumps(model['strings'])
Exemplo n.º 17
0
  def MakePage(self, template_file, language, extra_params=None):
    root_page = "/"

    if language is None:
      language = self.GetLanguageFromRequest()
    else:
      root_page = "/%s/" % language

    if language is None:
      language = 'en'

    i18n.get_i18n().set_locale(language)

    if extra_params is None:
      extra_params = {}

    # i18n
    self.response.headers['Content-Language'] = i18n.get_i18n().locale

    # Add extra display information to the list of downloads
    downloads = copy.deepcopy(DOWNLOADS)
    for d in downloads:
      self.ComputeDownloadInfo(d)

    # Add datetime objects to the list of news
    news = copy.deepcopy(NEWS)
    for n in news:
      title = n['title']
      content = n['content']
      n['datetime'] = datetime.datetime.fromtimestamp(n['timestamp'])
      n['title'] = i18n.gettext(title)
      n['content'] = i18n.gettext(content)

    screenshots = copy.deepcopy(SCREENSHOTS)
    for s in screenshots:
      for e in s['entries']:
        title = e['title']
        e['title'] = i18n.gettext(title)

    # Try to detect the user's OS and architecture
    ua = self.request.headers['User-Agent'].lower()
    if 'win' in ua:
      best_download = self.FindDownload('windows')
    elif 'mac' in ua:
      best_download = self.FindDownload('mlion')
    elif 'fedora' in ua:
      if '64' in ua:
        best_download = self.FindDownload('fedora16', 64)
      else:
        best_download = self.FindDownload('fedora16', 32)
    elif 'maverick' in ua:
      if '64' in ua:
        best_download = self.FindDownload('umaverick', 64)
      else:
        best_download = self.FindDownload('umaverick', 32)
    elif 'lucid' in ua:
      if '64' in ua:
        best_download = self.FindDownload('ubuntu', 64)
      else:
        best_download = self.FindDownload('ubuntu', 32)
    else:
      best_download = None

    # Translate the best download strings
    if best_download is not None:
      self.ComputeDownloadInfo(best_download)

    languages = [{'code': x, 'name': LANGUAGE_NAMES[x], 'current': x == language} for x in LANGUAGES]

    params = {
      'best_download':      best_download,
      'downloads':          downloads,
      'latest_downloads':   [x for x in downloads if x['ver'] == LATEST_VERSION],
      'latest_screenshots': screenshots[0]['entries'],
      'latest_version':     LATEST_VERSION,
      'news':               news,
      'language':           language,
      'languages':          languages,
      'old_downloads':      [x for x in downloads if x['ver'] != LATEST_VERSION],
      'root_page':          root_page,
      'screenshots':        screenshots,
      'is_rtl':             language == 'ar' or language == 'fa' or language == 'he',
    }
    params.update(extra_params)

    template = jinja_environment.get_template(template_file)
    self.response.out.write(template.render(params))
Exemplo n.º 18
0
 def gettext(self, string):
     return i18n.gettext(string)
Exemplo n.º 19
0
    def MakePage(self, template_file, language, extra_params=None):
        root_page = "/"

        if language is None:
            language = self.GetLanguageFromRequest()
        else:
            root_page = "/%s/" % language

        if language is None:
            language = 'en'

        i18n.get_i18n().set_locale(language)

        if extra_params is None:
            extra_params = {}

        # i18n
        self.response.headers['Content-Language'] = i18n.get_i18n().locale

        downloads = self._FetchRelease()

        # Add datetime objects to the list of news
        news = copy.deepcopy(NEWS)
        for n in news:
            title = n['title']
            content = n['content']
            n['datetime'] = datetime.datetime.fromtimestamp(n['timestamp'])
            n['title'] = i18n.gettext(title)
            n['content'] = i18n.gettext(content)

        screenshots = copy.deepcopy(SCREENSHOTS)
        for s in screenshots:
            for e in s['entries']:
                title = e['title']
                e['title'] = i18n.gettext(title)

        # Try to detect the user's OS and architecture
        ua = self.request.headers['User-Agent'].lower()
        if 'win' in ua:
            best_download = self.FindDownload(downloads, 'windows', 32)
        elif 'mac' in ua:
            best_download = self.FindDownload(downloads, 'mac', 64)
        elif 'fedora' in ua:
            if '64' in ua:
                best_download = self.FindDownload(downloads, 'fedora', 64)
            else:
                best_download = self.FindDownload(downloads, 'fedora', 32)
        else:
            best_download = None

        languages = [{
            'code': x,
            'name': LANGUAGE_NAMES[x],
            'current': x == language
        } for x in LANGUAGES]

        params = {
            'best_download':
            best_download,
            'downloads':
            downloads,
            'latest_downloads':
            [x for x in downloads if x['ver'] == LATEST_VERSION],
            'latest_screenshots':
            screenshots[0]['entries'],
            'latest_version':
            LATEST_VERSION,
            'news':
            news,
            'language':
            language,
            'languages':
            languages,
            'old_downloads':
            [x for x in downloads if x['ver'] != LATEST_VERSION],
            'root_page':
            root_page,
            'screenshots':
            screenshots,
            'is_rtl':
            language == 'ar' or language == 'fa' or language == 'he',
        }
        params.update(extra_params)

        template = jinja_environment.get_template(template_file)
        self.response.out.write(template.render(params))
Exemplo n.º 20
0
 def test_gettext(self):
     self.assertEqual(i18n.gettext('foo'), u'foo')
Exemplo n.º 21
0
 def gettext(self, string):
     """Gettext handler."""
     return gettext(string)
Exemplo n.º 22
0
 def gettext(self, string):
     return i18n.gettext(string)
Exemplo n.º 23
0
 def test_gettext(self):
     self.assertEqual(i18n.gettext("foo"), "foo")
Exemplo n.º 24
0
 def test_gettext_with_variables(self):
     self.assertEqual(i18n.gettext("foo %(foo)s"), "foo %(foo)s")
     self.assertEqual(i18n.gettext("foo %(foo)s") % {"foo": "bar"}, "foo bar")
     self.assertEqual(i18n.gettext("foo %(foo)s", foo="bar"), "foo bar")
Exemplo n.º 25
0
 def gettext(self, string):
     return gettext(string)
Exemplo n.º 26
0
    def get(self):
        locale = self.request.GET.get('locale', 'en_US')
        i18n.get_i18n().set_locale(locale)

        #would be nicer to get a dict with translation keys from i18n if possible...
        template_values = {
            'locale' : locale,
            'title' : i18n.gettext('Wordbank search aggregator'),
            'Search' : i18n.gettext('Search'),
            'exact' : i18n.gettext('exact'),
            'searchLink' : i18n.gettext('searchLink'),
            'On' : i18n.gettext('On'),
            'Off' : i18n.gettext('Off'),
            'About' : i18n.gettext('About'),
            'titleAbout' : i18n.gettext('About the wordbank search aggregator'),
            'aboutContents1' : i18n.gettext('aboutContents1'),
            'aboutContents2' : i18n.gettext('aboutContents2'),
            'aboutContents3' : i18n.gettext('aboutContents3'),
            'aboutContents4' : i18n.gettext('aboutContents4'),
            
            'titleSettings' : i18n.gettext('titleSettings'),
            'legendInterfaceLanguage' : i18n.gettext('legendInterfaceLanguage'),
            'English' : i18n.gettext('English'),
            'Icelandic' : i18n.gettext('Icelandic'),
            'Continue' : i18n.gettext('Continue'),
            'titleCharges' : i18n.gettext('titleCharges'),
            'chargesHeading' : i18n.gettext('chargesHeading'),
            'chargesContents' : i18n.gettext('chargesContents')
        }
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))