简体   繁体   中英

Is it possible to multipurpose a Twig template?

I am learning to use Slim framework and Twig. I want to know if it is possible to kind of multi-purpose a template.

Consider this; I want to make a form to add a job for a client, if you access via the 'job/new' route it would output a select list of clients to choose a client for whom the job is intended.

If however, you access via the 'job/new/:id' route it would render the same template but with only the client that the 'id' value corresponds to.

        {% for client in clients %}
        <option value="{{ client.id }}">{{ client.name }}</option>
        {% endfor %}

The above will work when I use:

     $data['clients'] = Client::find('all');
     $app->render('job/new.html',$data);

However, in my other route:

     $data['clients'] = Client::find($id);
     $app->render('job/new.html',$data);

As there is only 1 record it does not seem to output. I just wanted to save pulling all clients and multi-purpose the same template.

If this is not possible I know that I can pull all clients and send in the ID to select the client on the second route, or, create a different template that does not use the select and just send the single client to it.

Thanks

Ok I post the correct answer here, not just in the comments.

The Client::find('all'); gives back an array of elements, but the Client::find($id); gives only a single element. If you want to use the same template with the iteration you have to put the result into an array like this: $data['clients'] = array(Client::find($id));

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