Enhance Page Content Dynamically with Symfony2 and Ajax-Like Functionality

When assessing an ArrayCollection in my Template, I am currently using the following loop:

{% for article in articles %}
   <li
      {% if article.new %}
         class="new"
      {% endif %}
   >{{ article.name|e }}</li>
{% endfor %}

My goal now is to refresh the articles ArrayCollection without reloading the entire page, similar to how it is done in Ajax. Is it feasible to refresh it and have twig evaluate all the articles in a loop as shown above?

I aim to utilize twig for content evaluation

Answer №1

Achieving this is definitely possible. All you need to do is send an ajax request to the corresponding action that will return the rendered collection for you. There are a couple of ways to go about this:

You can either create a new action (recommended), or you can add new parameters to the request that will inform twig about which part to render or not (easier but harder to maintain).

Edit

I am extending my answer at the request of the author.

For example, let's consider a News controller in the YourNs\YourBundle namespace. The contents might look something like this:

class NewsController extends Controller
{

    /**
     * @Route("/articles")
     * @Template()
     */
     public function listAction(){
         $articles = $this->yourMethodToFindArticles();
         return compact('articles');
     }
}

The next step would be to render this action by creating a

YourNs/YourBundle/Resources/views/News/list.html.twig
file and populating it accordingly.

Once you have completed this step, you will need to implement the functionality to trigger an ajax request in order to retrieve a refreshed collection of articles. The FOSJsRouting bundle might come in handy for this purpose.

You can either add a new action to the controller:

    /**
     * @Route("/_api/articles-list")
     * @Template()
     */
     public function apiListAction(){
         $articles = $this->yourMethodToFindArticles();
         return compact('articles');
     }

And then have its template render only the collection.

Alternatively, you can parameterize your initial action and adjust the template accordingly:

{% if app.request.query.get('partial') %}
Template elements
{% endif %}
{% for article in articles %}
<li
  {% if article.new %}
     class="new"
  {% endif %}
>{{ article.name|e }}</li>
{% endfor %}
{% if app.request.query.get('partial') %}
Other template elements
{% endif %}

The second solution is less favorable compared to the first one, particularly when you start utilizing esi tags. In that case, your code would look like this:

class NewsController extends Controller
{

    /**
     * @Route("/articles")
     * @Template()
     */
     public function listAction(){
         return [];
     }

    /**
     * @Route("/_api/articles-list")
     * @Template()
     */
     public function apiListAction(){
         $articles = $this->yourMethodToFindArticles();
         return compact('articles');
     }
}

And the template for listAction():

Template elements
{{ render_esi(url('yourns_yourbundle_news_apilist' }}
Other template elements

Please note that the snippets provided above are simplified solutions for explaining a straightforward issue.

Edit2

Here is an example of fetching using FOSJsRouting, including the js code with the api action:

var url = Routing.generate('yourns_yourbundle_news_apilist')
var fetchedCollection = $.get(url);

And an example with a parameterized template:

var url = Routing.generate('yourns_yourbundle_news_list', {'partial': 'true'})
var fetchedCollection = $.get(url);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to display a variable in JavaScript on an HTML textarea

I'm working on a JavaScript variable called 'signature' var signature; //(Data is here) document.write(signature) Within my HTML document, I have the following: <div id="siggen"> <textarea id="content" cols="80" rows="10">& ...

Next JS is successfully importing external scripts, however, it is failing to run them as

In my upcoming project using the latest version 12.1.6, I am incorporating bootstrap for enhanced design elements. The bootstrap CSS and JS files have been included from a CDN in the pages/_app.js file as shown below: import '../styles/globals.css&apo ...

The issue seems to be that the Ajax and Ruby script is only displaying one record instead of multiple

While attempting an Ajax call using Ruby and Sinatra, I encountered an issue where the query should return multiple rows but only returns one. The ajax script in use is: $(document).ready(function() { $(".showmembers").click(function(e) { e. ...

Change the selection box to a checkbox

I am struggling to retrieve the value of a selection box inside jQuery. Specifically, I need to access the selection box value within a function that triggers on a checkbox change event: This is what I have so far: $('input').on('change& ...

Does Vuejs emit an event when a specific tab becomes active in boostrap-vue?

I am looking for a way to display and hide a section on my page when a specific tab is active, and close it when the tab is inactive. I have tried using the forceOpenSettings and forceCloseSettings methods for opening and closing the div. Is there an event ...

Utilize JavaScript to redirect based on URL parameters with the presence of the "@ symbol"

I need help redirecting to a new page upon button click using a JS function. The URL needs to include an email address parameter. <form> <input type="email" id="mail" placeholder="ENTER YOUR EMAIL ADDRESS" requir ...

What seems to be the issue with this Discord.js kick command code? It's not

Okay, so I'm in the process of creating a kick command for my Discord bot. The issue I'm encountering is that when no reason is specified or if a user is not mentioned to be kicked, the bot responds correctly but does not actually kick the user. ...

When using mongoose, is it possible to add a new item and retrieve the updated array in one endpoint?

My API endpoint for the post operation query using mongoose is not returning the updated array after adding a new item. I have been struggling with this issue for 3 days without any success. Any help would be greatly appreciated. router.post("/:spot ...

Setting up an OnMouseOver event for each URL on a webpage

Is there a way to add an OnMouseOver event for all anchor tags on a page, without replacing any existing event handlers that are already in place? I'm looking for guidance on how to achieve this using JavaScript or JQuery. Any suggestions would be gr ...

Using Python with Selenium and JavaScript for Logging in

When using Selenium and Python, I am attempting to log in to a website but encountering difficulties. The issue is that the source code does not display the necessary Id=apple_Id required for sending login information, although it can be seen when inspecti ...

Individualize participants and thwart repetition

I need help separating 3 radio players using HTML code and ensuring they remain distinct entities. What code should I use between them to achieve this? For example, all 3 radio players end up looking like the last one at the bottom if not separated correc ...

What is the best way to conceal a website's URL?

Is it possible to hide the actual URL some.otherdomain.com and show only domain.com to visitors of my website? I am looking for a way to mask the URL, perhaps through .htaccess or javascript. Is there any solution available? ...

When a user clicks, they will be directed to the specific product page using Angular UI router

On my homepage, I have a JSON feed where all the products are displayed. When clicking on a specific product image, I want it to redirect to a separate page showing only that particular product. I understand that changes need to be made in the singleproduc ...

ES modules' `require()` functionality is not supported

Issue: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: D:\...\node_modules\normalize-url\index.js [0] require() of ES modules is not supported. [0] require() of D:\...\node_modules\normalize-url\index.js ...

The Jquery function for selecting a div added by an Ajax call is not functioning properly, but it works fine without the need for an

I have a unique checkbox that I created using an Ajax call. The issue I'm facing is that the jQuery to select the checked input in the second div #test_checkbox_ajax isn't working, while it works perfectly fine in the first div #test_checkbox. Cr ...

Attaching identical class and event handlers to numerous dynamically created elements

I am facing a challenge with the following HTML structure: <a href="#" @click.prevent="toggleClass">Show/Hide</a><br> <li :class="{myClass: showItems}">Item 1</li> <a href="#" @click.prevent="toggleClass">Show/Hide< ...

Execute a batch operation or transaction within a Cloud Firestore onCreate trigger

Imagine a scenario where I have a collection of vendor documents in firestore: vendors : { vendor1: { id: "vendor1", name: "John", shopId: "shop1" }, vendor2: { id: "vendor2", name: "Mary", shopId: "shop2" } } Additionally ...

When hovering over a div, reveal another div on top of a third div

Imagine two adjacent divs, A on the left and B on the right with some other elements in between. Is it possible to have a third div, C, appear over div A when hovering over div B? I can control the display property using CSS, but I am unsure how to make d ...

What are the best practices for correctly implementing Angularjs ng-repeat?

As a newcomer to angularjs, I am in the process of building an app where the output is already set up correctly. However, I am looking to achieve the same without relying on jQuery, and instead want to utilize the angularjs method using "ng-repeat". Below ...

Motion of the atoms

I recently came across an interesting effect on the IconArchive website, but I am unsure how to implement it. If anyone could help me understand the concept with a small example, that would be greatly appreciated. You can see the effect in action by visi ...