javascriptphphtmltwigblogs

How can i know which link i clicked in an HTML


I am using PHP and Twig to create a blog for practice, I want to be able to access a post for it to display completely on a new URL, for this I use a route to '/indiv' which using a controller renders a new page, what I want is to be able to access any post and display it using only one '.twig' file, however I don't seem to find a way to find out which post was clicked, I know it has something to do with $_GET or $_POST however I don't know how to get the id of the post, some help would be greatly appreciated.

{% extends "layout.twig" %}

 {% block content %}
    {% for blogPost in blogPosts %}
        <div class="blog-post">
        <a href={{'/indiv' | url}}> <h2> {{blogPost.title}} </h2> </a>
        
            <form method="get"> 
            <lable for="id"></lable>
            <input class="btn btn-primary" type="submit" value="GotoPost">
            <a href={{'/indiv' | url}}> </a>
            </input>
            </form>
            
            <p> Jan 1, 2020 by <a href=""> Alex </a> </p>
            
            {% if blogPost.img_url %}
                <div class="blog-post-image">
                    <img src={{blogPost.img_url}} alt="">
                </div>
            {% endif %}
            
        </div>
    {% endfor %}
 {% endblock %}

Solution

  • one way:

    you have to alter your route so it accepts a parameter

    /indiv/{id}
    

    and in your html you send the id of the clicked post

    <a href='/indiv/{{blogPost.id}}>
    

    another way:

    as i can see in your code, you are sending data in a form so you can send the id of the post as well in the form using <input type="hidden" value="{{blogPost.id}}"

    i never used Twig so the syntax might be wrong but this is the logic to be used.