Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to use fix_html_in_content_fields without applying the default html_fixer #231

Merged
merged 1 commit into from
Nov 19, 2023

Conversation

pbauer
Copy link
Member

@pbauer pbauer commented Nov 19, 2023

This way you can use it in upgrade-steps
e.g:

def upgrade(setup_tool=None):
    from collective.exportimport.fix_html import fix_html_in_content_fields

    fixers = [text_img_align_fixer]
    fix_html_in_content_fields(fixers=fixers, apply_default_fixer=False)


def text_img_align_fixer(text, obj=None):
    """Replace inline-styles for img tags with classes."""
    from bs4 import BeautifulSoup

    if not text:
        return text

    replaced_styles = {
        "float: left": "image-left",
        "float: right": "image-right",
    }
    soup = BeautifulSoup(text, "html.parser")
    for tag in soup.find_all("img"):
        styles = tag.get("style", "").split(";")
        styles = [i.strip() for i in styles if i.strip()]
        if not styles:
            continue

        new_classes = []
        old_classes = tag.get("class", [])

        for old, new in replaced_styles.items():
            if old in styles:
                styles.remove(old)
                new_classes.append(new)
                if "image-inline" in old_classes:
                    old_classes.remove("image-inline")

        if new_classes:
            tag["class"] = old_classes + new_classes

        if styles:
            tag["style"] = ";".join(styles)
        else:
            del tag["style"]
    return soup.decode()

@pbauer pbauer merged commit 58b2bc4 into main Nov 19, 2023
11 checks passed
@pbauer pbauer deleted the allow-skip-html-fixer branch November 19, 2023 12:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant