mel47 Posted October 10, 2022 Posted October 10, 2022 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
bernhard Posted October 10, 2022 Posted October 10, 2022 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.
mel47 Posted October 10, 2022 Author Posted October 10, 2022 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; }
bernhard Posted October 10, 2022 Posted October 10, 2022 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} 2
mel47 Posted October 10, 2022 Author Posted October 10, 2022 Thanks! I tried many versions, but apparently I missed those ones... ?
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now