Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Building Websites with PHP Contact Form & Sending Email Testing For POST Data

PHP in twig?

So if i write php code in the twig file like this:

{% block something %}

    <?php (some php code) ?>
     (Some html code)

{% endblock something %}

I works for the html code. It won't work for the php code... Is there any simple way to make twig execute the php code?

That is a good question. I assumed you could put PHP in the block, but have not actually tried. Have you used Google to try to find the answer? If you find one please post the answer because I will want to do the same thing in the future.

2 Answers

So apparently this is not possible directly but I solved it in one way. I translated my PHP code into twig code... I know this is a lame solution if you have large PHP files but I don't know, the {% include 'file.php' %} didn't really work. So for example, the PHP code:

?php $mac_book_air = array('MacBook', 'PC'); ? <optgroup label="Macbook Air"> <?php foreach( $mac_book_air as $mac_air ){ ?> <option value="<?php echo $mac_air ?>"><?php echo $mac_air ?></option> <?php } ?> </optgroup>

would be this in twig:

{% set mac_book_air = [ 'MacBook', ''PC'] %}

{% for key, user in mac_book_air %} <option value="{{user}}">{{ user }}: {{ user.username|e }}</option> {% endfor %}

So basically I looked up the array and for loop syntaxes for twig and translated...

I WOULD APPRECIATE IF SOMONE FOUND A BETTER ANSWER ! ! !

The whole point of using a template system is that you dont have php in it. Use twig syntax instead

    {% for user in users %}
        {{ loop.index }} - {{ user.username }}
    {% endfor %}