So If I understand you have lets say 10 image on each image you want to attach a different single modal, in this way you have 10 modal in the code
At first I want to underline that is quite inefficient. You are going to replicate the modal several time overloading the html and javascript code.
But probably you know better than me your need as I do not have the whole picture of your project.
When I see public function getModalContent… I think you want to put this code in some classes.
I would use a simple function unless you foresee to do some more complicated and put more logic in the class.
I guess you wan to assign it directly to a variable and the echo it somewhere which is not possible as Modal::begin() and Modal::end() do an echo
But if instead doing something like:
$myModal=getModalContent($model, $attribute);
echo $myModal;
you can put getModalContent($model, $attribute); in the place where you need to echo it in the view you should achieve the same.
Another thing you can try is to play a bit with output buffering but I would avoid as it can interfere with yii output buffering if not properly managed.
Anyway buffering is stackable so something like the following should work properly:
function getModalContent($model, $attribute) {
ob_start(); //start a new buffer
Modal::begin([/*** my modal init **/ ]);
/*
* modal content
*/
Modal::end();
return ob_get_clean(); // get the output of the last buffer opened and close it
}