Alex
Alex

Reputation: 73

how to translate inside a loop using flask-babel

I'm having a hard time figuring out how to use flask-babel to translate variables inside a loop. Give this (non-working) example what would I need to change for each iteration to have it's own translation?

{% for key, values in products.items() %}
    <h4>{{ _('%(name)s', name=values['name']) }}</h4>
    <p>{{ _('%(caption)s', caption=values['caption']) }}</p>
{% endfor %}

With this example the PO is generated like:

msgid "%(name)s"
msgstr ""

This, as far as I know, only allows me to insert a single value for the translation

Upvotes: 1

Views: 973

Answers (1)

Dauros
Dauros

Reputation: 10517

So you have static and dynamic texts. The Babel-way to translate texts is only effective for static texts. For dynamically generated texts it would be very ineffective: Babel does not know about the dynamic texts, you would have to add manually the news text to the PO each time when a new product appears. I don't recommend it.

You should use a different approach for dynamic texts. I guess that you periodically import the products into your DB through a 3rd party API so you have a Product model. If there are only a few languages and texts to translate, it's still adequate to have only one model with many translated-fields (one for each language). For example:

class Product(db.Model):
    __tablename__ = 'product'

    id       = db.Column(db.Integer, primary_key=True)
    category = db.Column(db.SmallInteger, index=True)
    added    = db.Column(db.DateTime, index=True)

    name_en  = db.Column(db.String(255))
    name_eo  = db.Column(db.String(255))
    name_hu  = db.Column(db.String(255))

    description_en = db.Column(db.Text)
    description_eo = db.Column(db.Text)
    description_hu = db.Column(db.Text)

So after you import new products, you can translate their texts through an online interface. If you have many fields to translate you can separate the language dependent and independent part of the Product, and have separated models for them:

class Product(db.Model):
    __tablename__ = 'product'

    id       = db.Column(db.Integer, primary_key=True)
    category = db.Column(db.SmallInteger, index=True)
    added    = db.Column(db.DateTime, index=True)

class ProductText(db.Model):
    __tablename__ = 'product'

    id          = db.Column(db.Integer, primary_key=True)
    pid         = db.Column(db.Integer, db.ForeignKey('product.id'))
    language    = db.Column(db.String(10), index=True)

    name        = db.Column(db.String(255))
    description = db.Column(db.Text)

Thus when you want to show a product to the client, first check the active language, and load the corresponding translated ProductText with the current Product.

Upvotes: 1

Related Questions