1

I currently have a template for the article content type.

node--article.tpl.php contains:

<?php
    print render($content['body']);
    print render($content['field_file']);
    print render($content['field_tags']);
?>

All of those fields are rendered just fine. All the values of field_tags are rendered. However I'd like to be able to refer to each individual value of the tags field.

For instance, I'd like to be able to do

    <span class="customClass i">field_tag</span>

and iterate i for each item the field spits out.

I've made some attempts with no luck. I tried

$i = 0;
while($content['field_tags']){
    print "<span class='customClass ".$i."'>";
    print render($content['field_tags']);
    print "</span>";
    $i += 1;
}

However that just created an infinite loop. I attempted it with

while(render($content['field_tags']))

as well but that created an infinite loop as well. Is there a way to access the tags field as an array? rather than just one element in the $content array?

1

I managed to accomplish this by appending [value] to the end of the field_tag array. Then by using the 'count' function I created a for loop to iterate through each value like so

$j = count($content['field_tags']);
for( $i = 0; $i < $j; $j+= 1){
    if(render($content['field_tags'][$i]) != ''){
        print "<span class='customClass ".$i."'>";
        print render($content['field_tags'][$i]);
        print "</span>";
    }
}

Note: For some reason I had to insert a check for if the tag was empty because the array ended up being a lot larger than the number of the tags.

  • 1
    Hey Matt, sure that is one possibility. But it's not the most elegant one. Normally you would try to keep the template files as untouched as possible and solve your problem by using one of Drupal's preprocess hooks like described there: digett.com/blog/01/18/2012/… – leymannx Aug 11 '15 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.