IfUsing this expression, if the line is fully within a polygon geometry, the @within
variable will return the the containing polygon and use its boundary as the placement. Otherwise, otherwise the original line geometry is used.
Change 'poly'
for your polygon layer name.
with_variable('within', overlay_within('poly', @geometry)[0],
case
when @within is not NULL
then @within
else @geometry
end
)