Nick Price
Nick Price

Reputation: 963

Symfony2/Twig - Outputting an array of data

I was wondering the best way to do something. My controller makes a call to a service's function. This function obtains some DOMDocument stuff and I didnt want to pass this whole response to twig. So what I do is this

public function terminalService($terminal_command)
{
    $dom = new \DOMDocument('1.0', 'UTF-8');
    $responseData = $this->commandsService->executeSingleCommand($terminal_command);
    $dom->loadXML($responseData);

    $elements = $dom->getElementsByTagNameNS('http://www.test.com/ter_0', 'Text');

    $elNum = 0;
    $flightInfo = array();

    while ( $elNum < $elements->length ) {
        $flightInfo[] = $elements->item($elNum)->nodeValue;
        ++$elNum;
    }

    return $flightInfo;
}

So that takes the DOMDocument, finds all the elements which have the Text namespace and places them into an array element. My controller then receives this array and then passes it to the view

$commandData = $apiService->terminalService($terminal_command);

return $this->render('NickAlertBundle:Page:terminal.html.twig', array(
     'data' => $commandData,
));

How can I get each element of the array displayed on a new line? In my view I am currently doing

<div class="col-md-8" id="terminal-window">
    {% if data is defined %}
        {% for d in data %}
            {{ d|nl2br }}
        {% endfor %}
    {% endif %}
</div>

All that does however is display everything in one long string. funny enough, if I dump data it displays it how I want (but I obviously cant do this in production). So how can I display each array element on its own line?

Update A dump displays the data how I want it displays e.g.

6 => "3*A$NZ9835 C4 D4 J4 Z4 B7 H7 M7 Y7 LHRLAX 1035 1350   *  777 0E"
7 => "           Q7 T7 V7 W7 G7 K7 L7 S7 "

So as you can see line 7 is displayed with a lot of spaces in order to format the output correctly. If I simply place a break at the end of my output, it displays like so

7 #AY4014 F9 A9 P9 J9 C9 D9 I9 Y9 LHRLAX 1215 1530 * 77W 0E
B9 H9 K9 M9 L9 V9 S9 N9 Q9 O9 G9 

Is there any way to retain the spaces or duplicate what a dump does?

Thanks

Upvotes: 0

Views: 66

Answers (1)

bassplayer7
bassplayer7

Reputation: 934

Since you have most of the logic set, I would change the for loop to this:

<div class="col-md-8" id="terminal-window">
    {% if data is defined %}
        {% for d in data %}
            <pre>{{ d }}</pre><br />
        {% endfor %}
    {% endif %}
</div>

Upvotes: 2

Related Questions