Laravel 表单方法 VS 传统编码

2022-01-08 00:00:00 php laravel laravel-4

我目前正在学习 Laravel,发现它非常有用且有趣.

I am currently learning Laravel and finding it really useful and interesting.

目前我正在制作一个简单的在线申请表.

At the moment I am making a simple online application form.

使用 Laravel 语法做事的最大优势是什么:

What are the biggest advantages to doing things using the Laravel syntax like:

{{ Form::open(array('url' => 'foo/bar')) }}

相对于简单的:

<form action="foo/bar">

或者:

echo Form::text('username');

代替:

<input type="text" name="username" />

Laravel的方式一定更好,我只是想知道为什么?

The Laravel way must be better, I just wish to know why exactly?

推荐答案

使用内置的 HTML 助手有很多好处:

Using built-in HTML helpers have many benefits:

  1. 使用 Form::open 添加 CSRF 保护输入隐藏(默认)

  1. Using Form::open you add CSRF protection input hidden (by default)

使用表单元素(inputs/textarea 等)和 withInput 方法进行重定向,让您可以轻松地用相同的数据填写表单,几乎无需编码

Using form elements (inputs/textarea etc.) and withInput method for Redirection allows you to easily fill in the form with the same data with almost no coding

如果你使用 Redirect::route('form'->withInput(); 并且有输入text {{Form::text('username')}} 它将自动将输入的值设置为旧数据 - 您无需自己编写代码检查它

If you use Redirect::route('form'->withInput(); and have input text {{Form::text('username')}} it will automatically set input's value the old data - you don't need to code it yourself checking it

此外,如果您想将字段与标签匹配起来会容易得多:

Also if you want to match fields with labels its much easier:

{{ Form::label('username', 'Enter username') }}
{{ Form::text('username') }}

它将生成以下代码:

<label for="username">Enter username</label>
<input name="username" type="text" id="username">

如您所见,id 将自动创建

so as you see id will be created automatically

可能还有更多.然而,主要的缺点是您需要学习并且它不便携,以防您想将您的网站移动到其他框架,但每个解决方案都有优点和缺点.

Probably there are some more. However the main disadvantage is that you need to learn and it's not portable in case you want to move your site to other Framework but each solution has pros and cons.

相关文章