Use jQuery to allow users to like/unlike posts with dynamic updates

- Only the pages that need jQuery and the likes.js script will load it
This commit is contained in:
Xevion
2022-03-30 01:18:42 -05:00
parent bfb69621e1
commit c5c3b01dfa
7 changed files with 69 additions and 6 deletions

View File

@@ -9,6 +9,25 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.5.0/js/all.min.js"
integrity="sha512-YUwFoN1yaVzHxZ1cLsNYJzVt1opqtVLKgBQ+wDj+JyfvOkH66ck1fleCm8eyJG9O1HpKIf86HrgTXkWDyHy9HA=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
{% if use_jquery %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
let csrf_token = "{{ csrf_token() }}";
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrf_token);
}
}
});
</script>
{% if use_likes %}
<script src="{{ url_for('static', filename='likes.js') }}"></script>
{% endif %}
{% endif %}
<link rel="preload" href="{{ url_for('static', filename='roadrunner_header.png') }}" as="image">
{% endblock %}
</head>

View File

@@ -1,5 +1,7 @@
{% extends 'layouts/index.html' %}
{% from 'macros.html' import render_field %}
{% set use_jquery = true %}
{% set use_likes = true %}
{% block content %}
{% if current_user.is_authenticated %}
@@ -13,15 +15,15 @@
<hr style="margin: 1.5em 0">
{% for post in posts %}
<div class="post-box">
<i class="fas fa-heart {% if current_user.has_liked_post(post.id) %}liked{% endif %}"></i>
<div id="post-{{ post.id }}" class="post-box">
<i class="fas fa-heart {% if current_user.has_liked_post(post.id) %}liked{% endif %}" onclick="like({{ post.id }})"></i>
{{ post.text }}
<div class="post-author no-border">
{% with comment_count = post.comments|length %}
<em>Posted by <a href="{{ url_for('main.view_user', username=post.author.username) }}">{{ post.author.name }}</a></em>
<span title="{{ post.date_posted }}">{{ post.get_time_ago() }} ago</span>. |
<a href="{{ url_for('main.view_post', post_id=post.id) }}"><span> {{ comment_count }} comment{{ comment_count|pluralize }}</span></a>
| {{ post.get_like_text()|safe }}
| <span class="post-like-status">{{ post.get_like_text()|safe }}</span>
{% endwith %}
</div>
</div>