如何修改Slim Response对象中的Twig模板数据?

时间:2017-10-26 15:38:12

标签: twig slim-3

有没有办法通过Response对象修改Twig / Slim的模板数据?否则,从失败的表单提交中加载和填充表单的建议策略是什么?

class Item extends Model {} // eloquent model
class ItemOption extends Model {} // eloquent model

class controller
{
    // this route is for loading the form and pre-populating it for editing
    public function getItemForEditing($request, $response)
    {
        $item = Item::find($request->getAttribute('id'));
        $options = ItemOption::all(); // this is to populate HTML select input

        return $this->view->render($response, 'edit-item.twig', [
            form => $item.toArray(),
            options => $options.toArray(),
        ]);
    }

    // this route is when edit form is submitted
    public function postItemForEditing($request, $response)
    {   
        $errors = $this->validate(...);
        if(!empty($errors))
        {
            // by reusing this route to get the response, 
            // I automatically take care of all the template data necessary
            // to be passed to the twig view
            $response = $this->getItemForEditing($request, $response);

            // this method does not exists, but if it does,
            // then I can just update/append any additional data from here
            $response->data([
                form => $request->getParams(), // replace DB values with latest inputs
                error => $errors,
            ]);

            // finally return the response
            return $response;
        }
        else
        {
            // update Item in database
            ...
        }
    }
}

// inside edit-item.twig template
<input type="text" value="{{ form.price }}">
<select>
    {% for option in options %}
    <option value="{{option.id}}" {% if option.id == form.option_id %}selected{% endif %}>{{option.name}}</select>
    {% endfor %}
</select>

0 个答案:

没有答案
相关问题