From 26e2630ddd4be0ff099be017d270f636e4c7288b Mon Sep 17 00:00:00 2001 From: Jaime Iniesta Date: Wed, 20 Aug 2025 19:38:16 +0200 Subject: [PATCH] fixes HTML issue for h1 containing p Introduces a helper to strip p tags where needed --- .../templates/post/post.html.heex | 2 +- lib/school_house_web/views/html_helpers.ex | 15 +++++++++++++++ test/school_house_web/views/html_helpers_test.exs | 10 ++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/school_house_web/templates/post/post.html.heex b/lib/school_house_web/templates/post/post.html.heex index df12e6c5..8b3f5d8c 100644 --- a/lib/school_house_web/templates/post/post.html.heex +++ b/lib/school_house_web/templates/post/post.html.heex @@ -15,7 +15,7 @@
-

<%= raw @post.title %>

+

<%= @post.title |> strip_p_tags() |> raw() %>

diff --git a/lib/school_house_web/views/html_helpers.ex b/lib/school_house_web/views/html_helpers.ex index 522e3ac0..4a05111b 100644 --- a/lib/school_house_web/views/html_helpers.ex +++ b/lib/school_house_web/views/html_helpers.ex @@ -99,4 +99,19 @@ defmodule SchoolHouseWeb.HtmlHelpers do def translation_status_css_class(%{status: :minor}), do: "bg-yellow-400" def translation_status_css_class(%{status: :patch}), do: "bg-yellow-200" def translation_status_css_class(_line), do: "bg-white" + + @doc """ + Removes all

and

tags from the given string, inserting newline if needed. + + This is useful to avoid nesting

tags inside elements that don't allow them like headings or span, + for example in the blog posts titles. + """ + def strip_p_tags(str) when is_binary(str) do + str + |> String.replace("

", "") + |> String.replace("

", "\n") + |> String.trim() + end + + def strip_p_tags(str), do: str end diff --git a/test/school_house_web/views/html_helpers_test.exs b/test/school_house_web/views/html_helpers_test.exs index c63f9800..7c5a69b8 100644 --- a/test/school_house_web/views/html_helpers_test.exs +++ b/test/school_house_web/views/html_helpers_test.exs @@ -69,4 +69,14 @@ defmodule SchoolHouseWeb.HtmlHelpersTest do assert 1 < length(locales) end end + + describe "strip_p_tags" do + test "removes

and

tags from string" do + assert HtmlHelpers.strip_p_tags("

some content

") == "some content" + end + + test "converts

tags to newline" do + assert HtmlHelpers.strip_p_tags("

one

two

") == "one\ntwo" + end + end end