Jump to content

Function with variation of fieldname (solved)


mel47
 Share

Recommended Posts

Hi,

For my new project, I'm trying to increase my optimization skills... So I have a template with fields
Name(title)
content_director
photo_director
content_prof
photo_prof
etc...
I want to write a function to render a identical markup (renderBio(PageArray $items, string $category)), but for pages director or prof. However I tried many ways and I'm not sure how to do. I could do it with many IF but I would prefer an other solution.
I tried to concatenate $item->content_ and $category but can't found the appropriate set of {}, "" or ''. 
If not I could use an array, but I'm not sure what to add in.
Or maybe find fieldname ending with $category?
What solution would you preconize?

Thanks. I'm eager to see your solutions!
Mel

Link to comment
Share on other sites

I don't understand what you are trying to do. Could you explain that a little more please? I understand parts of what you said but not everything and details are important ? 

Maybe you can provide a real example of what you have and what the expected output would be.

Link to comment
Share on other sites

Hi,
Thanks. I put what I've done but it didn't work and I'm not sure it's the best way.
 

function renderBio(PageArray $items, string $categorie) {
  $out = '';

  foreach ($items as $item) {

    $photo = ${"$item->image_".$categorie}; //should be $item->image_director
    $bio = ${"$item->content_".$categorie}; //should be $item->content_director


  $out .="<div class='article columns is-multiline border-horizontal is-vcentered'>
                  <h3>{$item->title}</h3>
                            <div class='column is-3'>
                                <img loading='lazy' src='{$photo->url}' alt='{$photo->description}'>
                            </div>
                            <div class='column is-9'>$bio</div>
                      </div>";
              }

          return $out;
}

 

Link to comment
Share on other sites

42 minutes ago, mel47 said:
$photo = ${"$item->image_".$categorie};

This would be the cleanest imho:

$photo = $item->get("image_" . $categorie);

You could also do this:

$property = "image_" . $categorie;
$photo = $item->$property;

Or this

$photo = $item->{"image_" . $categorie}
  • Like 2
Link to comment
Share on other sites

  • mel47 changed the title to Function with variation of fieldname (solved)

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...