fix: 목차를 이미지 뒤에 배치 + TOC 링크 없으면 숨김

- 목차가 대표이미지 위에 나오던 문제 수정 (이미지 → 목차 → 본문 순서)
- TOC에 실제 <a> 링크가 없으면 "목차" 제목만 나오는 현상 방지

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
JOUNGWOOK KWON
2026-03-30 18:59:26 +09:00
parent 8eb6b7a7f9
commit e1fb6c954a
2 changed files with 25 additions and 6 deletions

View File

@@ -96,9 +96,15 @@ def build_full_html(article: dict, body_html: str, toc_html: str,
json_ld = build_json_ld(article, post_url) json_ld = build_json_ld(article, post_url)
disclaimer = article.get('disclaimer', '') disclaimer = article.get('disclaimer', '')
parts = [json_ld] parts = [json_ld]
# 목차: h2가 3개 이상인 긴 글에서만 표시 # 목차: h2가 3개 이상이고 TOC에 실제 링크가 있을 때만 표시
h2_count = body_html.lower().count('<h2') h2_count = body_html.lower().count('<h2')
if toc_html and toc_html.strip() not in ('', '\n') and h2_count >= 3: toc_has_links = toc_html and '<a ' in toc_html and h2_count >= 3
if toc_has_links:
import re as _re
m = _re.match(r'(<img\s[^>]*/>)\s*', body_html)
if m:
body_html = m.group(0) + f'<div class="toc-wrapper">{toc_html}</div>\n' + body_html[m.end():]
else:
parts.append(f'<div class="toc-wrapper">{toc_html}</div>') parts.append(f'<div class="toc-wrapper">{toc_html}</div>')
parts.append(body_html) parts.append(body_html)
if disclaimer: if disclaimer:

View File

@@ -376,6 +376,16 @@ def fetch_featured_image(article: dict) -> str:
return '' return ''
def _insert_toc_after_image(body_html: str, toc_block: str) -> str:
"""본문에 대표이미지가 있으면 이미지 뒤에, 없으면 맨 앞에 TOC 삽입"""
import re as _re
# 본문 시작이 <img 태그이면 그 뒤에 삽입
m = _re.match(r'(<img\s[^>]*/>)\s*', body_html)
if m:
return m.group(0) + toc_block + body_html[m.end():]
return toc_block + body_html
def build_full_html(article: dict, body_html: str, toc_html: str) -> str: def build_full_html(article: dict, body_html: str, toc_html: str) -> str:
"""최종 HTML 조합: 대표이미지 + JSON-LD + 목차 + 본문 + 면책 문구""" """최종 HTML 조합: 대표이미지 + JSON-LD + 목차 + 본문 + 면책 문구"""
json_ld = build_json_ld(article) json_ld = build_json_ld(article)
@@ -399,10 +409,13 @@ def build_full_html(article: dict, body_html: str, toc_html: str) -> str:
body_html = img_tag + '\n' + body_html body_html = img_tag + '\n' + body_html
html_parts.append(json_ld) html_parts.append(json_ld)
# 목차: h2가 3개 이상인 긴 글에서만 표시 # 목차: h2가 3개 이상이고 TOC에 실제 링크가 있을 때만 표시
h2_count = body_html.lower().count('<h2') h2_count = body_html.lower().count('<h2')
if toc_html and toc_html.strip() not in ('', '\n') and h2_count >= 3: toc_has_links = toc_html and '<a ' in toc_html and h2_count >= 3
html_parts.append(f'<div class="toc-wrapper">{toc_html}</div>') if toc_has_links:
# 이미지 뒤, 본문 앞에 목차 삽입
toc_block = f'<div class="toc-wrapper">{toc_html}</div>\n'
body_html = _insert_toc_after_image(body_html, toc_block)
html_parts.append(body_html) html_parts.append(body_html)
# 원문 출처 링크 # 원문 출처 링크