I handle the context like this:
function wpse_216001_srcset() {
// generate your Srcset here and return
}
function wpse_216001_sizes() {
// generate your sizes attribute here and return
}
add_filter( 'wp_calculate_image_sizes', 'wpse_216001_sizes', 10 , 2 );
add_filter( 'wp_calculate_image_srcset', 'wpse_216001_srcset', 10 , 5);
// call one of the standard WP image output functions here
remove_filter( 'wp_calculate_image_sizes', 'wpse_216001_sizes', 10 );
remove_filter( 'wp_calculate_image_srcset', 'wpse_216001_srcset', 10 );
You can either do this in your template or make a wrapper function in your functions.php and then call this as a template tag.