When I was using this theme before, I found that if a code block was inserted at the beginning of an article, it would cause the entire homepage style to be abnormal during rendering. However, I didn't delve into this issue at the time and thought that writing a code block in the first line of the article was indeed not very elegant.
Now that I have some free time, I am preparing to fix bugs in the theme and have found that someone raised this issue, so it's a good opportunity to study it.
Why Does This Problem Occur?#
If you randomly create an index.md document and insert a segment of Markdown table syntax at the beginning of the article, the rendered page will have style issues. Opening the console and checking the index.html page in the source, you can see that the HTML tags for the table are not properly closed.
Here is a snippet of the code:
else if post.content
- var br = 0
- for (var i = 0; i < 5; ++i) {
- br = post.content.indexOf('\n',br+1)
if br<0
- break
if br >150
- break
- }
if br < 0
.post-content
!= post.content
else
.post-content
!= post.content.substring(0, br)
From the code, it can be seen that it is truncated at '\n', capturing five lines of code, and these five lines happen to truncate the table tag.
The HTML content part after truncation is shown below:
<div class="post-content">
<table>
<thead>
<tr>
<th>-</th>
<th>-</th>
</div>
<p class="readmore"><a href="/2020/01/21/hexo/hexo/">Read More</a></p>
Solution Ideas#
I have thought of several solutions regarding this issue.
Only Display Text#
Process the blog post as text, ignoring code blocks or images directly. Then capture part of the text as a summary for display.
Close Unclosed Tags#
Complete the truncated HTML tags through an algorithm. I have implemented this functionality while fixing bugs, but found it was not as useful as I imagined. For example, the table tag might be closed when no content is displayed in a line. It is also possible that a five-line table list only displays one line, and upon clicking, you find several more lines. A good visual effect is that images and code blocks can also be displayed as summaries.
Continue Matching Unclosed Tags#
The idea here is that if a tag is not properly closed in the current truncated line, continue matching to the next line until the article is completely matched to the closing tag. I have basically implemented this functionality while fixing bugs, but discovered more issues, such as img, br, and a tags being single tags, or it might continue matching until the end of the article to find the correct closing tag. Additionally, using regex to match HTML tags is quite troublesome; I have not found a correct rule yet and may need to continue learning, although some say regex cannot match HTML.
Final Solution#
Later, while referencing the methods of other themes, I realized that only displaying text might be a better approach. I used the helper function strip_html provided by Hexo to handle document truncation.