1

I need to generate url to be able to load some content in html element.

$('#editSchool').click(function () {
            var id = $(this).attr('data-id');

Problem starts here when I try to insert id value for id parameter

            $('#educationDialog').load("{{ path('_education_edit', {'id': id}) }}", function () {
                $('.closeDialog, #person_education_form_cancel').click(function () {
                    $('#addSchool').trigger('click');
                });
            });
        });

Do you have some solution, if this is possible?

1
  • Please state clearly the problem and desired behaviour. Commented Jan 6, 2017 at 11:14

2 Answers 2

2

The problem was very simple. Instead of passing data-id attribute, data-url can be passed.

<span id="editSchool" data-url="{{ path('_education_edit', {'id': id}) }}">  
     Edit School
</>

$('#editSchool').click(function () {
        var url = $(this).data('url');

        $('#educationDialog').load(url, function () {
            $('.closeDialog, #person_education_form_cancel').click(function () {
                $('#addSchool').trigger('click');
            });
        });
    });
Sign up to request clarification or add additional context in comments.

Comments

1

The twig is parsed when the page is rendered, so the id variable in your route declartion is set when the page loads.

The easiest fix is to change your route to accept a nullable parameter for the id, then add the id to the route in your JavaScript. Also, for use in JavaScript, you will need to use the url twig function as it gives an absolute url, path gives a relative url. Ref: What is the difference between 'url' and 'path' in symfony2.3

Example routing.yml;

my_route:
    path:    /foo/bar/{id}
    defaults:   { _controller: AppBundle:Foo:bar, id: null }

Then in your twig;

<script>
var url = '{{ url('my_route') }}'+'/';
var id = $(this).attr('data-id'); 
$('#educationDialog').load(url+id, function () {
    // ...
});
</srcipt>

3 Comments

you should avoid putting your javascript in the twig template
@t-n-y where do you put your JavaScript and why should putting it in a twig file be avoided?
it s better to separate you javascript in js files. It should be avoided to separate the code, just like you avoid putting css in the html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.