简体   繁体   中英

How to dynamically access objects in a twig template with symfony2

I don't even know what title use to this question. I'm starting with web programming and I don't even know what technology should I use to do this.

I have a database with doctrine in symfony2. This database has galleries and each gallery has images (two tables OneToMany relation).

I'm passing an array of galleries to a twig template where I show them in a select, so I can choose one and add more images to the gallery, add new galleries or delete them using the submit buttons.

That is working now with this template:

<select class="listGalleries" id="listGalleries" name='id' size="10">
{% for gallery in galleries %}
    <option value="{{gallery.id}}" >{{gallery.name}}</option>
{% endfor %}
</select>

That goes inside the form.

Now, what I want to do is everytime I do click in one item of the select, show, in the same webpage, all the images of the gallery selected.

I don't know which technology should I use. Can I do it with twig? Do I have to learn ajax? I guess I have to go to the database to read the data of the pictures that belongs to that gallery, but I don't know how to do it or if symfony2 offers me a better solution.

Every advice will be appreciated.

"Dynamically" can't be done in twig, since after its rendering there is no way to change the output.

You can do in two ways in my opinion:

Use twig to loop within galleries and output them, then use some javascript like bootstrap tabs to display each gallery when changing option. in bootstrap you would do this way (assuming the gallery->images relations is in $gallery->images):

<div class="tab-content">
    {% for gallery in galleries %}
        <div class="tab-pane active" id="gallery{{ gallery.id }}">
             {% for image in gallery.images %}
                 <img src="{{ image.url }}" class="img-polaroid">
             {% endfor %}
        </div>
    {% endfor %}
</div>

now using javascript like

$("select#listGalleries").change(function () {
    $("select option:selected").each(function () {
        $("#gallery" + $(this).attr('value')).tab('show');
    });
})

Otherwise you can use ajax to return the gallery images after having selected a gallery from the and render the gallery images somewhere on the page. This could be done in two ways, render the html within symfony and just place the output in the page with javascript or return just a json (using something like this ) and create the html within javascript (I personally use a lot pure ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM