Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4, Twig & VueJS - Redirecting to Symfony routes in Vue component

I am getting started with Symfony 4 using Twig templating and VueJS for UI components.

I have a very basic component in a .vue file for listing tasks, which currently renders a basic table.

// task-list.vue

<template>
    <div>
        <table class="table table-bordered table-striped">
            <thead>
            <tr>
                <th>
                    Task
                </th>
                <th>
                    Description
                </th>
                <th>
                    Completed?
                </th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="task in parsedTasks">
                <td>
                    {{ task.title }}
                </td>
                <td>
                    {{ task.description }}
                </td>
                <td>
                    {{ task.completed ? 'Yes' : 'No' }}
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    export default {
      name: 'task-list',
      props: {
        tasks: {required: true}
      },
      computed: {
        parsedTasks() {
          return JSON.parse(this.tasks);
        }
      },
    };
</script>

This component is registered in the root JS file;

// assets/js/app.js

Vue.component('task-list', TaskList);

new Vue({
  el: '#app-root'
});

This is then used in a Twig template;

// tasks/list.html.twig

...
<task-list tasks="{{ tasks | json_encode }}"></task-list>
...

I want to be able to use the path() Twig function so that, when a row in the task list is clicked, the user is redirected to the generated route/path. Is this possible given that the Vue component is not in a Twig file?

As a side question, is there a better way to pass a Twig variable to a Vue component than json encoding then parsing the data as above?

like image 706
James Crinkley Avatar asked Dec 09 '17 01:12

James Crinkley


Video Answer


1 Answers

There is two main approaches: Generate the URL in the backend and use it in javascript:

var route = "{{ path('blog_show', {'slug': 'my-blog-post'})|escape('js') }}";

https://symfony.com/doc/current/routing/generate_url_javascript.html

Or using a javascript routing library that integrates with symfony routes like FOSJsRouting:

var url = Routing.generate('blog_show', {
    'slug': 'my-blog-post'
});

https://github.com/FriendsOfSymfony/FOSJsRoutingBundle

like image 114
albert Avatar answered Oct 16 '22 18:10

albert