Azima
Azima

Reputation: 4141

render html with dynamic variable values with dompdf

I am trying to pass values to variables in template view file, and load the html using dompdf.

But the passed values are not evaluated and rendered.

Here's my Controller function:

    $dompdf = new Dompdf();
    $this->f3->set('user_name', 'Ross Geller');
    $this->f3->set('total_amount_due', 2270.00);
    $this->f3->set('amount_received', 1000.00);
    $this->f3->set('remaining_amount', 1270.00);
    $this->f3->set('received_by',  'Rakesh Mali');
    $this->f3->set('received_on', '2018-06-05 06:00:00');

    $template = new \View;
    $html =  $template->render('lunch/invoice.html');
    $dompdf->loadHtml($html);

// (Optional) Setup the paper size and orientation
    $dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
    $dompdf->render();

// Output the generated PDF to Browser
    $dompdf->stream();

Template file (invoice.html):

<label class="control-label col-sm-2" for="email">A/C Payee:</label>
<div class="col-sm-3">
    {{@user_name}}
</div>

<label class="control-label col-sm-2" for="pwd">Pending Total Amount:</label>
<div class="col-sm-10"> 
    Rs. <span class="amount_holder">{{@total_amount_due}}</span>
</div>

This is what is rendered:

A/C Payee:
{{@user_name}}
Pending Total Amount:
Rs. {{@total_amount_due}}

How can the html be loaded with the values set?

Upvotes: 1

Views: 4757

Answers (1)

Liam G
Liam G

Reputation: 597

Include the html template file, but as a PHP file.. then refer to the variables as you would in the PHP script using $ instead of @

Example

    $dompdf = new Dompdf();
    $user_name = 'Ross Geller';
    $total_amount_due = 2270.00;

    ob_start();
    require('invoice_template.php');
    $html = ob_get_contents();
    ob_get_clean();
    $dompdf->loadHtml($html);

// (Optional) Setup the paper size and orientation
    $dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
    $dompdf->render();

// Output the generated PDF to Browser
    $dompdf->stream();

Then in the invoice_template.php file have the following;

<label class="control-label col-sm-2" for="email">A/C Payee:</label>
<div class="col-sm-3">
    <?=$user_name?>
</div>

<label class="control-label col-sm-2" for="pwd">Pending Total Amount:</label>
<div class="col-sm-10"> 
    Rs. <span class="amount_holder"><?=$total_amount_due?></span>
</div> 

Upvotes: 1

Related Questions