How to Implement text_from_html() in Odoo?


What is text_from_html()?

text_from_html() is a utility function in Odoo that converts HTML content into plain text by stripping all HTML tags.

This function is particularly useful when you want to extract clean, human-readable content from fields that store HTML (such as mail.body, description, or website_description).


✅ Import Path

from odoo.tools import text_from_html

✅ Syntax

plain_text = text_from_html(html_string)

  • html_string: A string that contains HTML.

  • Returns: A plain text string with HTML tags removed.


📌 Realistic Use Cases in Odoo

1. Convert HTML Email Body to Plain Text (e.g., for SMS or Logging)


from odoo.tools import text_from_html

for message in self.message_ids:

    plain_body = text_from_html(message.body)

    _logger.info("Message content:\n%s", plain_body)


This ensures clean logging without HTML formatting.


2. Clean Website Descriptions for Export


from odoo.tools import text_from_html


products = self.env['product.template'].search([])

for product in products:

    clean_description = text_from_html(product.website_description)

    # Write to CSV/Excel with clean text

Useful when generating product reports or syncing data with external systems.


 3. SMS Gateway Integration

Most SMS gateways require plain text. You can clean an email body before sending it via SMS:


html_body = record.body_html

sms_text = text_from_html(html_body)

sms_api.send_message(to=record.partner_id.phone, message=sms_text)



✅ Summary Table


Function

Purpose

Use Case

text_from_html()

Strip HTML and return plain text

Email → SMS, Website description → clean text