flectra/addons/web_editor/models/ir_translation.py

48 lines
2.0 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
2018-01-16 11:34:37 +01:00
# Part of Odoo, Flectra. See LICENSE file for full copyright and licensing details.
from lxml import etree
2018-01-16 11:34:37 +01:00
from flectra import models, api
from flectra.tools.translate import encode, xml_translate, html_translate
def edit_translation_mapping(data):
data = dict(data, model=data['name'].partition(',')[0])
return '<span data-oe-model="%(model)s" data-oe-translation-id="%(id)s" data-oe-translation-state="%(state)s">%(value)s</span>' % data
class IrTranslation(models.Model):
_inherit = 'ir.translation'
@api.model
def _get_terms_mapping(self, field, records):
if self._context.get('edit_translations'):
self.insert_missing(field, records)
return edit_translation_mapping
return super(IrTranslation, self)._get_terms_mapping(field, records)
@api.multi
def save_html(self, value):
""" Convert the HTML fragment ``value`` to XML if necessary, and write
it as the value of translation ``self``.
"""
assert len(self) == 1 and self.type == 'model'
mname, fname = self.name.split(',')
field = self.env[mname]._fields[fname]
if field.translate == xml_translate:
# wrap value inside a div and parse it as HTML
div = "<div>%s</div>" % encode(value)
root = etree.fromstring(div, etree.HTMLParser(encoding='utf-8'))
# root is html > body > div
# serialize div as XML and discard surrounding tags
value = etree.tostring(root[0][0], encoding='utf-8')[5:-6]
elif field.translate == html_translate:
# wrap value inside a div and parse it as HTML
div = "<div>%s</div>" % encode(value)
root = etree.fromstring(div, etree.HTMLParser(encoding='utf-8'))
# root is html > body > div
# serialize div as HTML and discard surrounding tags
value = etree.tostring(root[0][0], encoding='utf-8', method='html')[5:-6]
return self.write({'value': value})