feat: add like count display on homepage and thumbs-up toggle on detail page
- Display like count with thumbs-up emoji on post cards in index.html
- Add clickable like/unlike button with JS fetch on post_detail.html
- Add POST /web/posts/{slug}/like endpoint in web routes for cookie-auth users
- Guests redirected to /auth/dev-login on 401
- Use block extra_js (matching base template) for inline script
This commit is contained in:
@@ -33,6 +33,13 @@
|
||||
{% else %}
|
||||
<span class="badge" data-testid="post-detail-status">{{ _('post.status_draft', current_locale) }}</span>
|
||||
{% endif %}
|
||||
<span class="post-card-meta-item" data-testid="post-detail-like-count">
|
||||
<button id="like-button" class="btn-like" data-testid="like-button"
|
||||
data-post-slug="{{ post.slug }}"
|
||||
data-liked="false">
|
||||
👍 <span id="like-count">{{ post.like_count }}</span>
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -83,3 +90,42 @@
|
||||
</footer>
|
||||
</article>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script data-testid="like-script">
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
var likeButton = document.getElementById('like-button');
|
||||
if (!likeButton) return;
|
||||
|
||||
likeButton.addEventListener('click', function() {
|
||||
var slug = this.getAttribute('data-post-slug');
|
||||
var countSpan = document.getElementById('like-count');
|
||||
|
||||
fetch('/web/posts/' + slug + '/like', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Accept': 'application/json'
|
||||
}
|
||||
})
|
||||
.then(function(response) {
|
||||
if (response.status === 401) {
|
||||
window.location.href = '/auth/dev-login';
|
||||
return;
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error('Like request failed');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(function(data) {
|
||||
if (data && data.like_count !== undefined) {
|
||||
countSpan.textContent = data.like_count;
|
||||
}
|
||||
})
|
||||
.catch(function(error) {
|
||||
console.error('Like error:', error);
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
Reference in New Issue
Block a user