如何在Laravel Blade模板中编写PHP代码?

3

我正在为一个使用Laravel框架的网站编写代码。虽然在Blade模板中编写PHP代码不被推荐,但由于时间紧迫,我只能这样做。

@php
   if($_POST["submit"]){
        $name = $_POST["name"];
        $email = $_POST["email"];

        $missingName = "<p><strong>Please eneter your name.</strong></p>";
        $invalidEmail = "<p><strong>Invalid Email.</strong></p>";


        if($name){
            $name = filter_var($name, FILTER_SANITIZE_STRING);
        }else{

            $errors .= $missingName;
        }


          $email = filter_var($email, FILTER_SANITIZE_EMAIL);
          $email = filter_var($email, FILTER_VALIDATE_EMAIL);
         if(filter_var($email, FILTER_VALIDATE_EMAIL)){

          }else{
              $errors .= $invalidEmail;
          }
        if($errors){
            $resultMessage = '<div  class="alert alert-danger">' . $errors .'</div>';
        }else{

            $to = "leads@relevant.systems";
            $subject = "DijiJock update request form.";
            $message = "<html>
                         <body>
                         <h2 style='color:black'>DijiJock update request form.</h2>
                <p style='color:green'>Name: $name</p>
                <p style='color:green'>Email: $email</p>
                <p style='color:black'>$name has requested DijiJock updates, please forward all updates to $email.</p>
                         </body>
                       </html>";
            $headers = "Content-type: text/html";


            if(mail($to, $subject, $message, $headers)){
                $resultMessage = '<div  class="alert alert-success">Thank you for the meesage!</div>';

            }else{
                $resultMessage = '<div  class="alert alert-warning">Email not sent! Please try again later.</div>';
            }
        }
        echo $resultMessage;
    }             
@endphp

中间的PHP代码不能正常工作吗?

似乎我使用了正确的标签,但是出现了“未定义的索引:submit”错误。 - Russell
尝试使用以下代码:if( isset($_POST["submit"]) )。这样做可以避免在页面加载时出现未定义的情况,因为此时表单尚未提交。 - nithinTa
1
你应该把这段代码放在控制器(Controller)中,而不是 .blade 文件里。 - Option
2个回答

3

在这里最好在控制器中实现操作,你可以创建一个帮助类,通过服务提供者进行绑定,然后使用它。

在某些情况下,将PHP代码嵌入视图中非常有用。您可以使用Blade @php指令在模板中执行一块纯PHP代码:

@php
    //
@endphp

这与以下内容完全相同:

<?php

?>

如果您需要共享全局变量,最好的方法是使用 View facadeshare() 方法,并在 service provider 上执行。详情请参考https://laravel.com/docs/5.7/views#passing-data-to-views

ex of use case: nested structure for layouts => save global variables with short names, that point to bigger name of tree traversal (+ easy to maintain when we alter the structure, do it once). ex:

namespace App\Providers;

use Illuminate\Support\Facades\View;

class ViewGlobaleVarServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    { // \/\/\/\/\/\/\/\/  <====== !
        View::share('sysAdmDashPgContainerHeader', 'system.admin.dashboard.partials.pageContainer.partials._header');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Here i created a new ServiceProvider, you can use too existing one, like the AppServiceProvider.

If the action to execute is depending on the controller calling, better implement things on controllers, if it's view specific (internal logic). Then @php @endphp is a nice way to achieve that.

Also for sharing variable Know that we can simply use @php @phpend in a layout view (it will be available on all included partials and object that extend it). So you know the nature of @include and @yield,@extend on that matter. However that's not the best practice or recommended. What's recommended is to use the helper View::share() above.

The other way to write code is to create your own directive:

(note all you need is to create one function on a service provider, and you have your own directive, )

And What about sharing function globally? Create and Use a global helper. By creating a file that will contain all the helpers (functions). Then either use the composer** auto loading**. Or bind an include_once through a service provider.


1
使用控制器和Blade视图方法。
Mail::send('emails.YOUR_BLADE_FILE', ['user' => $user, 'request' => $request], function ($message) use ($user, $request) {
     $message->to('EMAIL_ACCOUNT', 'EMAIL_USER_NAME');         
     $message->subject('EMAIL SUBJECT');
});

尝试使用这个函数。它非常简单和干净。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接