If your code doesn’t work in the widget, then something is wrong with your code. The widget just runs the code as-is, it doesn’t perform magic tricks.
In your case, the “$post” variable is not defined because you failed to declare it as a global. Code in templates run in the global variable scope. Code in the widget will run inside a function scope, and you need to account for that difference.