Skip to content

Commit 65cc1b9

Browse files
authored
fixes HTML issue for h1 containing p (#243)
Introduces a helper to strip p tags where needed
1 parent 353e03b commit 65cc1b9

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

lib/school_house_web/templates/post/post.html.heex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
</div>
1616

1717
<div class="pt-6 text-center">
18-
<h1 class="text-2xl leading-8 font-extrabold tracking-tight sm:text-2xl prose dark:prose-dark"><%= raw @post.title %></h1>
18+
<h1 class="text-2xl leading-8 font-extrabold tracking-tight sm:text-2xl prose dark:prose-dark"><%= @post.title |> strip_p_tags() |> raw() %></h1>
1919
</div>
2020

2121
<div class="py-2 text-center">

lib/school_house_web/views/html_helpers.ex

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,4 +99,19 @@ defmodule SchoolHouseWeb.HtmlHelpers do
9999
def translation_status_css_class(%{status: :minor}), do: "bg-yellow-400"
100100
def translation_status_css_class(%{status: :patch}), do: "bg-yellow-200"
101101
def translation_status_css_class(_line), do: "bg-white"
102+
103+
@doc """
104+
Removes all <p> and </p> tags from the given string, inserting newline if needed.
105+
106+
This is useful to avoid nesting <p> tags inside elements that don't allow them like headings or span,
107+
for example in the blog posts titles.
108+
"""
109+
def strip_p_tags(str) when is_binary(str) do
110+
str
111+
|> String.replace("<p>", "")
112+
|> String.replace("</p>", "\n")
113+
|> String.trim()
114+
end
115+
116+
def strip_p_tags(str), do: str
102117
end

test/school_house_web/views/html_helpers_test.exs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,14 @@ defmodule SchoolHouseWeb.HtmlHelpersTest do
6969
assert 1 < length(locales)
7070
end
7171
end
72+
73+
describe "strip_p_tags" do
74+
test "removes <p> and </p> tags from string" do
75+
assert HtmlHelpers.strip_p_tags("<p>some content</p>") == "some content"
76+
end
77+
78+
test "converts </p> tags to newline" do
79+
assert HtmlHelpers.strip_p_tags("<p>one</p><p>two</p>") == "one\ntwo"
80+
end
81+
end
7282
end

0 commit comments

Comments
 (0)